Władysław Adamczak
Władysław Adamczak

Reputation: 13

Disable a specific of flat rate shipping method for a selected product in Woocommerce

In Woocommerce, How can I turn off dynamically one specific "flat rate" for a specific selected product?

Eg.
I have three different flat rate options.
Product A can be sent using option 1, 2 and 3.
Product B can be sent using options 1 and 2.

Any help is appreciated.

Upvotes: 1

Views: 1258

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254383

This can be done with the following function code, where you will define the related product ID and the shipping method ID to be disabled.

To find out the correct shipping method ID, just inspect with your browser dev tools the corresponding "flat rate" radio button under "value" argument.

You may have to "Enable debug mode" in general shipping settings under "Shipping options" tab, to disable shipping caches.

The code:

add_filter('woocommerce_package_rates', 'product_hide_shipping_method', 10, 2);
function product_hide_shipping_method( $rates, $package ){
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return $rates;

    // HERE set your Shipping Method ID to be removed
    $shipping_method_id = 'flat_rate:12';

    // HERE set your targeted product ID
    $product_id = 37;

    $found = false;

    // Loop through cart items and checking for the specific product ID
    foreach( $package['contents'] as $cart_item ) {
        if( $cart_item['data']->get_id() == $product_id )
            $found = true;
    }

    if( $found ){
        // Loop through available shipping methods
        foreach ( $rates as $rate_key => $rate ){
            // Remove the specific shipping method
            if( $shipping_method_id === $rate->id  )
                unset($rates[$rate->id]);
        }
    }
    return $rates;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

Don't forget to re-enable "Enable debug mode" option in shipping settings.


For an array of several product IDs… replace the lines:

// HERE set your targeted product ID
$product_id = 37; 

with:

// Define your targeted product IDs
$product_ids = array(37, 39, 52, 58);

And replace the line:

if( $cart_item['data']->get_id() == $product_id )

with:

if( in_array( $cart_item['data']->get_id(), $product_ids ) )

Last thing for variable products: If you prefer to handle the parent variable product ID instead of the product variation IDs, replace in the code:

$cart_item['data']->get_id()

with:

$cart_item['product_id']

Upvotes: 1

Related Questions