If there are more than 15 articles in a cart. How can I force just one desired shipping method (i.e. DHL) and hide all other shipping methods?
I already have the plugin "flexible shipping" but prefer a hook in functions.php.
The following will enable only one defined shipping method if there is more than 15 articles in cart:
add_filter( 'woocommerce_package_rates', 'hide_shipping_methods_based_on_item_count', 10, 2 );
function hide_shipping_methods_based_on_item_count( $rates, $package ) {
// HERE the targeted shipping method ID (see the attribute "value" of the related shipping method input field)
$targeted_method_id = 'flat_rate:12'; // <== Replace with your DHL shipping method ID
// HERE the articles count threshold
$more_than = 15;
// Cart items count
$item_count = WC()->cart->get_cart_contents_count();
if( WC()->cart->get_cart_contents_count() > $more_than ) {
foreach ( $rates as $rate_key => $rate ) {
if ( $rate->id != $targeted_method_id ) {
unset($rates[$rate_key]);
}
}
}
return $rates;
}
Code goes on function.php file of your active child theme (or theme). Tested and works.
Refresh the shipping caches: (required)
- This code is already saved on your active theme's function.php file.
- The cart is empty
- In a shipping zone settings, disable / save any shipping method, then enable back / save.
You are done and you can test it.