skip to Main Content

I have enabled WooCommerce Subscriptions plugin in My WooCommerce shop.

Following Set the shipping method in WooCommerce Subscriptions renewal orders answer code to my previous question, I would like to remove the Chronopost shipping method when a user has a product with a subscription on his cart.

Currently there are three different shipping methods and I want to keep the Colissimo domicile and Point Relais only.

Here are the shipping rate keys for each shipping method:

  • Colissimo domicile (gratuit): lpc_nosign:6
  • Chronopost domicile 24h: chrono13
  • Point relais (gratuit)"; chronorelais

In red you can see the method that i want to delete when the subscription is selected

2

Answers


  1. Chosen as BEST ANSWER

    I finally found how to resolve this by using the following code :

    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $product       = $cart_item[ 'data' ];
        $supports_args = array(
          'cart_item'     => $cart_item,
          'cart_item_key' => $cart_item_key
        );
    
        $produit_abo_key[] = WCS_ATT_Product_Schemes::get_subscription_scheme( $product );
    }
    
    if (!in_array(FALSE,$produit_abo_key)) $has_free_shipping = true;  
    
        if( $has_free_shipping ){
            if ($rate->method_id == 'chrono13') {
                unset($rates["chrono13"]);
            }
        }
    

  2. To hide a specific shipping method when there is a subscription product in cart, use:

    // Conditional function: Check if cart has a subscription
    function has_subscription_product( $cart_contents ) {
        foreach ( $cart_contents as $item ) {
            if ( $item['data']->is_type( array('subscription', 'subscription_variation') ) ) {
                return true;
            }
        }
        return false;
    }
    
    // Hide shipping  method conditionally
    add_filter( 'woocommerce_package_rates', 'filter_package_shipping_rates', 10, 2 );
    function filter_package_shipping_rates( $rates, $package ) {
        $targeted_id = 'chrono13'; // Here define the targeted shipping method rate ID
    
        // If there is a subscription in cart
        if( has_subscription_product( WC()->cart->get_cart() ) && isset($rates[$targeted_id]) ) {
            unset($rates[$targeted_id]); // Hide the shipping method
        }
        return $rates;
    }
    

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

    Important: You will have to empty your cart to refresh shipping method cache.

    Sort shipping methods displayed in WooCommerce Cart and Checkout

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search