I’m trying to unset Flat Rate shipping method only if cart has products both with and without shipping class. If all product in cart have shipping class then it should stay.
Have this shipping method: Flat Rate - (flat_rate1) (instance_id=1)
And these shipping classes: 50, 100 and so on, with same way named Slugs: 50, 100…
Flat Rate shipping method has costs set up for these shipping classes, Main Cost and No shipping class cost for this method are not set, so it only appears for products in cart that have shipping classes set.
Got it working
add_filter( 'woocommerce_package_rates', 'unset_shipping_for_unmatched_items', 100, 2 );
function unset_shipping_for_unmatched_items( $rates, $package ) {
// Initialisation
$shipping_classes = array( 50, 100, 150, 200, 250, 300 );
$cart_items = WC()->cart->get_cart();
$cart_items_count = WC()->cart->get_cart_contents_count();
$items_match = false;
$inArray = 0;
$notInArray = 0;
foreach( $cart_items as $cart_item ){
if( in_array( $cart_item[ 'data' ]->get_shipping_class(), $shipping_classes ) && $cart_items_count > 1 ) {
$inArray++;
} else {
$notInArray++;
}
}
if( ( $cart_items_count == $notInArray ) || ( $cart_items_count == $inArray ) ){
$items_match = false;
} else {
$items_match = true;
}
if( $items_match )
unset( $rates['flat_rate:6'] );
return $rates;
}
In WooCommerce the shipping methods ID slugs are a little different, I mean there is a typo error. You will need to add :
between the name and the number in the slug: 'flat_rate6'
.
Also once you get a matching cart item shipping class, you can break
the loop.
Last thing: This hook has 2 available arguments: $rates
and $package
.
So your code will be:
add_filter( 'woocommerce_package_rates', 'hide_shipping_when_class_is_in_cart', 100, 2 );
function hide_shipping_when_class_is_in_cart( $rates, $package ) {
// Initialisation
$shipping_classes = array( 50, 100, 150, 200, 250, 300 );
$class_exists = false;
foreach( WC()->cart->get_cart() as $cart_item )
if( in_array( $cart_item[ 'data' ]->get_shipping_class_id(), $shipping_classes ) ) {
$class_exists = true;
break; // Stop the loop
}
if( $class_exists )
unset( $rates['flat_rate:6'] );
return $rates;
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This should work now.