admin管理员组文章数量:1389762
In WooCommerce, I was trying to disable free shipping when certain items were added to the cart. I figured out a solution, and I've shared it as a posted answer below.
In WooCommerce, I was trying to disable free shipping when certain items were added to the cart. I figured out a solution, and I've shared it as a posted answer below.
Share Improve this question edited Feb 27, 2020 at 19:40 Winch asked Feb 27, 2020 at 19:39 WinchWinch 112 bronze badges1 Answer
Reset to default 1My solution is based off of this source snippet: https://www.xadapter/woocommerce-hide-shipping-methods-if-items-of-specific-shipping-class-is-not-in-cart/
I created a new Shipping class in WooCommerce called "no-free-shipping" (the slug is important as this must be replaced in the code if you have something different.)
In the functions.php file in your WordPress theme, add the following code:
add_filter('woocommerce_package_rates', 'xa_hide_shipping_method_when_shipping_class_product_is_in_cart', 10, 2);
function xa_hide_shipping_method_when_shipping_class_product_is_in_cart($available_shipping_methods, $package){
// Shipping class IDs that need the method removed
$shipping_classes = array(
'no-free-shipping',
);
$shipping_services_to_hide = array(
'free_shipping:1'
);
$shipping_class_exists = false;
foreach(WC()->cart->cart_contents as $key => $values) {
if (in_array($values['data']->get_shipping_class() , $shipping_classes)) {
$shipping_class_exists = true;
break;
}
}
// Negation of shipping class exists.
if($shipping_class_exists) {
foreach($shipping_services_to_hide as & $value) {
//echo var_dump($available_shipping_methods);
unset($available_shipping_methods[$value]);
}
}
return $available_shipping_methods;
}
My biggest problem was determining what the name of my "free shipping" option was, because there isn't a clearly defined slug in WooCommerce. To find this, I used the commented out
echo var_dump($available_shipping_methods);
To print out the name of the shipping option (in my case, "free_shipping:1") which I included in the code to get it working.
Now, if any product with the "no-free-shipping" shipping class is added to the cart, the free shipping option is removed.
本文标签: pluginsConditional Shipping Options if Certain Products are in Cart WooCommerce
版权声明:本文标题:plugins - Conditional Shipping Options if Certain Products are in Cart WooCommerce 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744710304a2621091.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论