1

I have a subscription based WordPress website and have different subscriptions. I'd like to when a user buy a new subscription the older one automatically canceled.

I used this code, but unfortunately all subscriptions were cancelled exept the new one.

add_action( 'woocommerce_thankyou', 'edf_cancel_previous_active_subscription' );
function edf_cancel_previous_active_subscription() {

$no_of_loops = 0;
$user_id = get_current_user_id();

// Get all customer subscriptions
$args = array(
    'subscription_status'       => 'active', 
    'subscriptions_per_page'    => -1,
    'customer_id'               => $user_id, 
    'orderby'                   => 'ID', 
    'order'                     => 'DESC'
);
$subscriptions = wcs_get_subscriptions($args);

// Going through each current customer subscriptions
foreach ( $subscriptions as $subscription ) {
    $no_of_loops = $no_of_loops + 1;

    if ($no_of_loops > 1){
        $subscription->update_status( 'cancelled' );
    } 
}

}

Is anyone has any suggestion to improve this code?

izsog
  • 11
  • 1

0 Answers0