Skip to content

Instantly share code, notes, and snippets.

@shameemreza
Last active January 11, 2025 05:03
Show Gist options
  • Save shameemreza/ed6ff1c664c497acbcc37e7892a03974 to your computer and use it in GitHub Desktop.
Save shameemreza/ed6ff1c664c497acbcc37e7892a03974 to your computer and use it in GitHub Desktop.
By default, WooCommerce Subscriptions require manual intervention to cancel a subscription to avoid accidental cancellations. However, we can cancel a subscription programmatically.
add_action( 'woocommerce_subscription_status_updated', 'auto_cancel_pending_cancellations', 10, 3 );
function auto_cancel_pending_cancellations( $subscription, $new_status, $old_status ) {
// Ensure we are dealing with a valid subscription object
if ( is_a( $subscription, 'WC_Subscription' ) ) {
// Check if the new status is 'pending-cancel'
if ( 'pending-cancel' === $new_status ) {
// Attempt to cancel the subscription
try {
$subscription->update_status( 'cancelled' );
// Optionally log the cancellation
error_log( 'Subscription ID ' . $subscription->get_id() . ' has been automatically cancelled.' );
} catch ( Exception $e ) {
// Log any errors
error_log( 'Error cancelling subscription ID ' . $subscription->get_id() . ': ' . $e->getMessage() );
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment