Hide the shipping methods if the cart does not have the specific shipping class
The code snippet facilitates you to hide the shipping methods. You can hide the shipping methods in a cart/checkout page if the cart does not have the product with the specific shipping class.
Add the following code to your functions.php or anywhere relevant.
add_filter(‘woocommerce_package_rates’, ‘hide_shipping_method_when_shipping_class_product_is_not_in_cart’, 10, 2); | |
function hide_shipping_method_when_shipping_class_product_is_not_in_cart($available_shipping_methods, $package) | |
{ | |
// Shipping class IDs that need the method removed | |
$shipping_class_ids = array( | |
27, | |
); | |
$shipping_services_to_hide = array( | |
‘wf_fedex_woocommerce_shipping:FEDEX_GROUND’, | |
‘wf_fedex_woocommerce_shipping:FEDEX_2_DAY_AM’ | |
); | |
$shipping_class_exists = false; | |
foreach(WC()->cart->cart_contents as $key => $values) { | |
if (in_array($values[‘data’]->get_shipping_class_id() , $shipping_class_ids)) { | |
$shipping_class_exists = true; | |
break; | |
} | |
} | |
if (!$shipping_class_exists) { | |
foreach($shipping_services_to_hide as & $value) { | |
unset($available_shipping_methods[$value]); | |
} | |
} | |
return $available_shipping_methods; | |
} |
In the above code:
– $available_shipping_methods contains all the available shipping methods for the carrier.
– $shipping_class_ids contains the IDs of the shipping class for which you need to hide the shipping services.
– $shipping_services_to_hide contains the list of shipping services which need to be hidden.
If $shipping_class_ids matches with the shipping class ID of the cart product, then $shipping_class_exists becomes true. If $shipping_class_exists is not true, then value of $available_shipping_methods is unset for all the listed shipping services. The Function returns $available_shipping_methods which hides the listed services on cart/checkout page.