使用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 文件中。经过测试并且可以工作。
刷新运输缓存:
- 此代码已保存在您的 function.php 文件中。
- 在运输区域设置中,禁用/保存任何运输方式,然后启用返回/保存。
您已完成,您可以对其进行测试。