Reputation: 105
From Disable specific shipping method if a cart item uses a specific shipping class ID answer code, how if there is another item in cart which does not have that shipping class ID and want to show flat_rate:2
again according to product shipping class?
Upvotes: 1
Views: 58
Reputation: 253939
You will use the following instead:
add_filter( 'woocommerce_package_rates', 'custom_hide_shipping_methods', 10, 2 );
function custom_hide_shipping_methods( $rates, $package ) {
$found = $others = false; // Initializing
$shipping_class_id = 513; // <== ID OF YOUR SHIPPING_CLASS
$shipping_rate_id = 'flat_rate:2'; // <== Targeted shipping rate ID
// Checking cart items for current package
foreach( $package['contents'] as $key => $cart_item ) {
$product = $cart_item['data']; // The WC_Product Object
if( $product->get_shipping_class_id() == $shipping_class_id ) {
$found = true;
} else {
$others = true;
}
}
if( $found && ! $others && isset($rates[$shipping_rate_id]) ) {
unset($rates[$shipping_rate_id]); // Removing specific shipping method
}
return $rates;
}
Code goes in functions.php file of your active child theme (or active theme). It should works.
Refresh the shipping caches:
- This code is already saved on your functions.php file.
- In a shipping zone settings, disable / save any shipping method, then enable back / save.
You are done and you can test it.
Upvotes: 1