免费送货基于WooCommerce中最少的购物车数量

时间:2020-06-22 15:56:22

标签: php wordpress woocommerce cart shipping-method

在Woocommerce中,我想根据购物车中唯一商品的数量提供免费送货。首先,我开始研究可用的插件,但找不到任何简单的解决方案。

我想要的是:如果访客将4个不同的商品添加到购物车中,则运费是免费的,但是例如,如果用户将相同的商品添加4次,则不是免费的。因此,基本上,它仅适用于4个不同的项目(具有4个不同的SKU编号)。

有什么建议吗?

1 个答案:

答案 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文件中。经过测试,可以正常工作。

刷新发货缓存:

  1. 此代码已保存在您的function.php文件中。
  2. 在运输区域设置中,禁用/保存任何运输方式,然后启用回退/保存。
    您已完成,您可以对其进行测试。