在Woocommerce中,我想根据购物车中唯一商品的数量提供免费送货。首先,我开始研究可用的插件,但找不到任何简单的解决方案。
我想要的是:如果访客将4个不同的商品添加到购物车中,则运费是免费的,但是例如,如果用户将相同的商品添加4次,则不是免费的。因此,基本上,它仅适用于4个不同的项目(具有4个不同的SKU编号)。
有什么建议吗?
答案 0 :(得分:1)
使用WooCommerce - Hide other shipping methods when FREE SHIPPING is available现有的答案代码,您只需要使用以下方法计算不同的订单项:
$items_count = count(WC()->cart->get_cart());
现在,您需要将免费送货方式设置设置为
N/A
(第一个选项);
然后,您将可以轻松更改代码,从而允许免费送货:
add_filter( 'woocommerce_package_rates', 'free_shipping_on_items_count_threshold', 100, 2 );
function free_shipping_on_items_count_threshold( $rates, $package ) {
$items_count = count(WC()->cart->get_cart()); // Different item count
$items_threshold = 4; // Minimal number of items to get free shipping
$free = array(); // Initializing
// Loop through shipping rates
foreach ( $rates as $rate_id => $rate ) {
// Find the free shipping method
if ( 'free_shipping' === $rate->method_id ) {
if( $items_count >= $items_threshold ) {
$free[ $rate_id ] = $rate; // Keep only "free shipping"
} elseif ( $items_count < $items_threshold ) {
unset($rates[$rate_id]); // Remove "Free shipping"
}
break;// stop the loop
}
}
return ! empty( $free ) ? $free : $rates;
}
代码进入活动子主题(或活动主题)的functions.php文件中。经过测试,可以正常工作。
如果您也想允许优惠券设置免费送货,则必须将免费送货设置更改为“ 最低订单金额或优惠券”, 0
最小订购量,使用以下代替:
add_filter( 'woocommerce_package_rates', 'free_shipping_on_items_count_threshold', 100, 2 );
function free_shipping_on_items_count_threshold( $rates, $package ) {
$items_count = count(WC()->cart->get_cart()); // Different item count
$items_threshold = 4; // Minimal number of items to get free shipping
$coupon_free_ship = false; // Initializing
$free = array(); // Initializing
// Loop through applied coupons
foreach( WC()->cart->get_applied_coupons() as $coupon_code ) {
$coupon = new WC_Coupon( $coupon_code ); // Get the WC_Coupon Object
if ( $coupon->get_free_shipping() ) {
$coupon_free_ship = true;
break;
}
}
// Loop through shipping rates
foreach ( $rates as $rate_id => $rate ) {
// Find the free shipping method
if ( 'free_shipping' === $rate->method_id ) {
if( $items_count >= $items_threshold || $coupon_free_ship ) {
$free[ $rate_id ] = $rate; // Keep only "free shipping"
} elseif ( $items_count < $items_threshold ) {
unset($rates[$rate_id]); // Remove "Free shipping"
}
break;// stop the loop
}
}
return ! empty( $free ) ? $free : $rates;
}
代码进入活动子主题(或活动主题)的functions.php文件中。经过测试,可以正常工作。
刷新发货缓存: