问题
In WooCommerce, I am hiding shipping methods based on different shipping classes in cart using "Hide shipping methods for specific shipping class in WooCommerce" answer code (the 2nd way), but the problem is that I use WPML plugin which manage 2 languages site, so looking for just one class won't do it.
So I need to handle 2 shipping classes instead of one. I tried addind 2 shipping classes this way:
// HERE define your shipping classes to find
$class = 3031, 3032;
But it breaks the website. So I would like to hide the defined flat rate not only for both shipping classes 3031
and 3032
.
What I am doing wrong? How can I enable 2 shipping classes without breaking the web site?
回答1:
To use multiple shipping classes, you should first defined them in an array and in the IF
statement you will use in_array()
conditional function this way:
add_filter( 'woocommerce_package_rates', 'hide_shipping_method_based_on_shipping_class', 10, 2 );
function hide_shipping_method_based_on_shipping_class( $rates, $package )
{
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// HERE define your shipping classes to find
$classes = [3031, 3032];
// HERE define the shipping methods you want to hide
$method_key_ids = array('flat_rate:189');
// Checking in cart items
foreach( $package['contents'] as $item ) {
// If we find one of the shipping classes
if( in_array( $item['data']->get_shipping_class_id(), $classes ) ){
foreach( $method_key_ids as $method_key_id ){
unset($rates[$method_key_id]); // Remove the targeted methods
}
break; // Stop the loop
}
}
return $rates;
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
Sometimes, you should may be need to refresh shipping methods going to shipping areas, then disable / save and re-enable / save your "flat rates" shipping methods.
Related thread: Hide shipping methods for specific shipping class in WooCommerce
来源:https://stackoverflow.com/questions/56406909/hide-shipping-methods-for-specific-shipping-classes-in-woocommerce