Search code examples
phpwoocommerceproducthook-woocommercewoocommerce-subscriptions

When Resubscribing, add a simple product in WooCommerce Subscriptions


I am using WooCommerce Subscriptions plugin

I have a Subscription product that is linked to a WooCommerce simple product with custom pricing as a package to customer.

During Subscription renewal, I programmatically add the simple product to the active subscription.

I have a scenario, where customer cancels the subscriptions and Admin approves the cancellation of subscription.

In that case, in the customer My account subscription page, It displays a Re-subscription button. This re-subscription only takes the last cancelled subscriptions Subscription product and proceeds to checkout.

Is there any way I can add the simple products also during the re-subscription process?

I tried the below hook, but it works after new subscription creation:

add_action('wcs_create_subscription', 'action_wcs_create_subscription', 10, 20)

Is there a way to hook in to re-subscription process and add additional simple products to the checkout?


Solution

  • You can easily detect when a re-subscription in cart.

    In the following code you will define the simple product ID to be added on re-subscription and the targeted subscription product ID in cart.

    The code will add your simple product to cart when a customer re-subscribe via its My account Subscriptions (for a specific product subscription).

    The code:

    add_action( 'woocommerce_checkout_init', 'add_product_with_resubscription' );
    function add_product_with_resubscription() {
        $cart = WC()->cart;
    
        $simple_product_id = 18; // Define the simple product ID to be added
        $subscr_product_id = 138; // Define the targeted product subscription ID
        $simple_is_in_cart = $is_resubscription = false; // Initializing
    
        // Loop through cart items
        foreach ( $cart->get_cart() as $item ) { 
            // Check for a specific resubscription
            if( isset($item['subscription_resubscribe']) 
            && in_array($subscr_product_id, [$item['product_id'], $item['variation_id']]) ) {
                $is_resubscription = true;
            }
            // Check that the simple product is not yet in cart
            if( $simple_product_id == $item['product_id'] ) {
                $simple_is_in_cart = true;
            }
        }
    
        // Add to cart the simple product and recalculate totals
        if ( $is_resubscription && !$simple_is_in_cart ) {
            $cart->add_to_cart($simple_product_id);
            $cart->calculate_totals();
        }
    }
    

    Code goes in functions.php file of your child theme (or in a plugin). Tested and works.