'Filtering out shipping method in WooCommerce [duplicate]
I'd like to force a specific shipping method when a condition is met in the cart (in my case the presence of some specific items), i.e to disable all methods except the specific one.
Thank you
Solution 1:[1]
add_filter('woocommerce_package_rates', 'force_shipping_for_specific_item', 100, 2);
function force_shipping_for_specific_item($rates, $package) {
$product_id = 1631819031; // specific item id
$shipping_method_id = 'free_shipping'; // specific shipping method
foreach ($package['contents'] as $cart_item) {
if (isset($cart_item['data']) && $product_id == $cart_item['data']->get_id()) {
$found = true;
break; // Stop the loop
}
}
if (!( isset($found) && $found ))
return $rates; // Exit
$allowed_shipping_method = array();
foreach ($rates as $rate_id => $rate) {
if ($shipping_method_id === $rate->method_id) {
$allowed_shipping_method[$rate_id] = $rate;
break;
}
}
return !empty($allowed_shipping_method) ? $allowed_shipping_method : $rates;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mujuonly |
