Skip to content

Instantly share code, notes, and snippets.

@WooForce
Created June 1, 2016 16:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WooForce/d117a8220dd34e72efeef24d2ac99f95 to your computer and use it in GitHub Desktop.
Save WooForce/d117a8220dd34e72efeef24d2ac99f95 to your computer and use it in GitHub Desktop.
Hide shipping methods when a shipping class is not available in the cart
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment