Search code examples
phpwordpresswoocommerceorderswoocommerce-subscriptions

Auto change Woocommerce Subscriptions status to "On-Hold" rather than "Active"


In Woocommerce, I would like to automatically put all Woocommerce Subscriptions "on hold" rather than "active" when the order is still "processing". Once I mark the order as "completed" that subscription should change to "active".

I've tried everything I can think of, if somebody knows how to do this please let me know.

I'm running wordpress 4.8.1 / Woocommerce 3.1.2 / Woocommerce Subscriptions 2.2.7 / and the payment gateway is Stripe 3.2.3.


Solution

  • This can be done in two steps:

    1) With a custom function hooked in woocommerce_thankyou action hook, when the order has a 'processing' status and contains subscriptions, we update the subscriptions status to 'on-hold':

    add_action( 'woocommerce_thankyou', 'custom_thankyou_subscription_action', 50, 1 );
    function custom_thankyou_subscription_action( $order_id ){
        if( ! $order_id ) return;
    
        $order = wc_get_order( $order_id ); // Get an instance of the WC_Order object
    
        // If the order has a 'processing' status and contains a subscription 
        if( wcs_order_contains_subscription( $order ) && $order->has_status( 'processing' ) ){
    
            // Get an array of WC_Subscription objects
            $subscriptions = wcs_get_subscriptions_for_order( $order_id );
            foreach( $subscriptions as $subscription_id => $subscription ){
                // Change the status of the WC_Subscription object
                $subscription->update_status( 'on-hold' );
            }
        }
    }
    

    Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

    2) With a custom function hooked in woocommerce_order_status_completed action hook, when the order status is changed to "completed", it will auto change the subscription status to "active":

    // When Order is "completed" auto-change the status of the WC_Subscription object to 'on-hold'
    add_action('woocommerce_order_status_completed','updating_order_status_completed_with_subscription');
    function updating_order_status_completed_with_subscription($order_id) {
        $order = wc_get_order($order_id);  // Get an instance of the WC_Order object
    
        if( wcs_order_contains_subscription( $order ) ){
    
            // Get an array of WC_Subscription objects
            $subscriptions = wcs_get_subscriptions_for_order( $order_id );
            foreach( $subscriptions as $subscription_id => $subscription ){
                // Change the status of the WC_Subscription object
                $subscription->update_status( 'active' );
            }
        }
    }
    

    Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

    All code is tested on Woocommerce 3+ and works.