Search code examples
phpwordpresswoocommercewoocommerce-subscriptions

How to cancel previous WooCommerce subscription automatically when new subscription is purchased?


I'm building a membership site where users must only have one active subscription at a time. I would like that on a purchase of any new subscription/product all other subscriptions to be cancelled/expired and all associated membership deleted/cancelled. Only the latest subscription should remain active with its accompanying membership.

I cannot/don't want to use the built-in function to limit subscriptions for several reasons.

Is there any way that on the thank you page, a snipped loops in all active subscriptions from current user and cancel/expire them, except for the one that has been just bought?

I've checked this post which looks similar but no real solution was provided (WooCommerce Subscriptions - Only Allow user one active subscription)

Thanks a lot for your help

Best regards


Solution

  • Auto-answering as I've managed to solve my issue with the help of other SO posts.

    Basically I'm getting all active subscriptions by descending ID and set a counter inside my loop. If it loops more than once then it sets the status of the subscription to cancelled. I hooked this in the thank you page to be sure it fires only when the payment has been made...

    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' );
            } 
        }
    }
    

    Not sure whether this is the "Wordpress/WooCommerce" way of doing it but I brought my other programming languages experience with me for this one. If someone has a better idea, feel free to post it.