Skip to content

Instantly share code, notes, and snippets.

@xadapter
Last active March 13, 2020 10:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xadapter/5abdd7005db919846001da36718b28ad to your computer and use it in GitHub Desktop.
Save xadapter/5abdd7005db919846001da36718b28ad to your computer and use it in GitHub Desktop.
Snippet to hide WooCommerce shipping methods if items of a specific shipping class is not present in the cart. Supports PluginHive Shipping Plugins: https://www.pluginhive.com/product-category/woocommerce-plugin/woocommerce-shipping/
// Snippet to hide WooCommerce shipping methods if items of a specific shipping class is not present in the cart
add_filter('woocommerce_package_rates', 'xa_hide_shipping_method_when_shipping_class_product_is_in_cart', 10, 2);
function xa_hide_shipping_method_when_shipping_class_product_is_in_cart($available_shipping_methods, $package){
// Shipping class IDs that need the method removed
$shipping_classes = array(
'free-shipping',
);
$shipping_services_to_hide = array(
'wf_shipping_usps:D_PRIORITY_MAIL',
'wf_shipping_usps:D_EXPRESS_MAIL',
'wf_shipping_usps:flat_rate_box_priority'
);
$shipping_class_exists = false;
foreach(WC()->cart->cart_contents as $key => $values) {
if (in_array($values['data']->get_shipping_class() , $shipping_classes)) {
$shipping_class_exists = true;
break;
}
}
// Negation of shipping class exists.
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