Using WooCommerce v3.2.4 on This site (here) (WP v4.9) and 11 products with the shipping class of Overweight/Oversize that have a flat rate applied to them:
$20 to Canada and $25 to the US.
All other products have flat rate shipping of $10 (Canada) and $15 (US), unless the order is over $100, then free shipping is applied automatically.
My client wants free shipping to be disabled if there are any overweight/oversize items in the cart. The problem is that the cart says there are no shipping methods available when there are a mix of regular and oversize items in the cart, and no shipping methods are applied.
I'm using XAdapter Woocommerce Shipping Table Rate plugin to apply the higher cost to the "Overweight" Shipping Classes.
I deactivated this plugin, as I realized I could just use the WooCommerce Shipping Zone settings to set a flat rate for specific shipping classes. See screenshot below:
I am using some code to:
- hide the free shipping and flat rates when the "Overweight" Shipping Class exists in the cart
- hide the "Overweight" Shipping Method if that class does not exist (163 being the id of the Shipping Class)…
Here is that code:
add_filter('woocommerce_package_rates', 'wf_hide_shipping_method_based_on_shipping_class', 100, 2);
function wf_hide_shipping_method_based_on_shipping_class($available_shipping_methods, $package){
$hide_when_shipping_class_exist = array(
163 => array(
'flat_rate:1',
'flat_rate:2',
'free_shipping:3',
'free_shipping:5'
)
);
$hide_when_shipping_class_not_exist = array(
163 => array( 'wf_woocommerce_shipping_pro:overweightoversizeoverweight')
);
$shipping_class_in_cart = array();
foreach(WC()->cart->cart_contents as $key => $values) {
$shipping_class_in_cart[] = $values['data']->get_shipping_class_id();
}
foreach($hide_when_shipping_class_exist as $class_id => $methods) {
if(in_array($class_id, $shipping_class_in_cart)){
foreach($methods as & $current_method) {
unset($available_shipping_methods[$current_method]);
}
}
}
foreach($hide_when_shipping_class_not_exist as $class_id => $methods) {
if(!in_array($class_id, $shipping_class_in_cart)){
foreach($methods as & $current_method) {
unset($available_shipping_methods[$current_method]);
}
}
}
return $available_shipping_methods;
}
Here is a list of IDs of the rates per shipping zone:
Canada
- Regular Flat rate | ID:
flat_rate:1
- Free Shipping | ID:
free_shipping:3
- Local Pickup | ID:
local_pickup:4
USA
- Regular Flat rate | ID:
flat_rate:2
- Free Shipping | ID:
free_shipping:5