Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Code snippet to assign a particular WooCommerce Shipping method based on your Product ID. Supported Plugin: https://www.pluginhive.com/product/woocommerce-fedex-shipping-plugin-with-print-label/
add_filter('woocommerce_package_rates', 'hide_shipping_method_if_particular_product_available_in_cart', 10, 2);
function hide_shipping_method_if_particular_product_available_in_cart($available_shipping_methods)
{
global $woocommerce;
// products_array should be filled with all the products ids
// for which shipping method (stamps) to be restricted.
$products_array = array(
101,
102,
103,
104
);
// You can find the shipping service codes by doing inspect element using
// developer tools of chrome. Code for each shipping service can be obtained by
// checking 'value' of shipping option.
$shipping_services_to_hide = array(
'wf_usps_stamps:US-FC',
'wf_usps_stamps:US-XM',
'wf_usps_stamps:US-MM',
'wf_usps_stamps:US-LM',
'wf_usps_stamps:US-PP',
'wf_usps_stamps:US-PS',
'wf_usps_stamps:US-CM',
'wf_usps_stamps:US-PM',
'wf_usps_stamps:US-EMI',
'wf_usps_stamps:US-PMI',
'wf_usps_stamps:US-FCI'
);
// Get all products from the cart.
$products = $woocommerce->cart->get_cart();
// Crawl through each items in the cart.
foreach($products as $key => $item) {
// If any product id from the array is present in the cart,
// unset all shipping method services part of shipping_services_to_hide array.
if (in_array($item['product_id'], $products_array)) {
foreach($shipping_services_to_hide as & $value) {
unset($available_shipping_methods[$value]);
}
break;
}
}
// return updated available_shipping_methods;
return $available_shipping_methods;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.