在Woocommerce中为两个或更多购物车启用免费送货 [英] Enable free shipping for two or more cart items in Woocommerce
问题描述
在Woocommerce中,我想根据购物车的数量提供免费送货服务。首先,我开始研究可用的插件,但找不到基于数量的简单解决方案。
In Woocommerce, I want to offer free shipping based on the number of cart items. First, I began looking at the available plugins and I can't find any simple solution based on quantity.
我要做的就是:购买2件,免费送货。
All I want to do is: buy 2 of anything and get free shipping.
我想找点时间尝试了以下代码:
Messing around, I tried the following code:
function free_ship( $is_available ) {
$count = 0;
global $woocommerce;
$items = $woocommerce->cart->get_cart();
foreach($items as $item) {
$count++;
}
echo $count;
if ( $count == 1 ) {
echo 'add one more for free shipping';
return $is_available;
} elseif ($count > 1) {
echo 'you get free shipping';
return false;
} else {
echo 'nothing in your cart';
return $is_available;
}
}
add_filter( 'woocommerce_shipping_free_shipping_is_available', 'free_ship' );
但是在将商品添加到购物车时挂起。从购物车中取出物品时,它也是有问题的。我想用PHP弄清楚这一点,以便我可以进一步添加更多独特的条件,以防将来它们突然出现。
But it hangs when adding items to the cart. It also is buggy when removing things from the cart. I'd like to figure this out in PHP, so that I can further add more unique conditions in they happen to pop up in the future.
有什么建议吗?
推荐答案
您的操作中有一些错误代码,例如缺少参数,复杂性和过时的事物……请尝试以下操作:
There are some mistakes in your code, like missing arguments, complications and outdated things… Try the following instead:
add_filter( 'woocommerce_shipping_free_shipping_is_available', 'free_shipping_for_x_cart_items', 10, 3 );
function free_shipping_for_x_cart_items( $is_available, $package, $shipping_method ) {
$item_count = WC()->cart->get_cart_contents_count();
if ( $item_count == 1 ) {
$notice = __("Add one more for free shipping");
$is_available = false;
} elseif ($item_count > 1) {
$notice = __("You get free shipping");
$is_available = true;
}
if ( isset($notice) ) {
wc_add_notice( $notice, 'notice' );
}
return $is_available;
}
此代码位于您的活动子主题(或活动主题)的function.php文件中主题)。经过测试和工作。
This code goes in function.php file of your active child theme (or active theme). Tested and works.
WC_Cart
方法 get_cart_contents_count()
获取所有商品的数量(包括数量)。
获取不同购物车商品的数量 (不包括数量),替换以下行:
$item_count = WC()->cart->get_cart_contents_count();
与此一起:
$item_count = sizeof($package['contents']);
这篇关于在Woocommerce中为两个或更多购物车启用免费送货的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!