基于 Woocommerce 中的购物车小计的分层运输

Tiered Shipping based on cart subtotal in Woocommerce

在 Woocommerce 中,我需要根据购物车小计设置运费,如下所示:

我有非常基本的 PHP 知识,并且修改了我找到的代码片段。

这是我的代码:

add_filter('woocommerce_package_rates','bbloomer_woocommerce_tiered_shipping', 10, 2 );
function bbloomer_woocommerce_tiered_shipping( $rates, $package){
    $threshold1 = 20;
    $threshold2 = 30;
    if ( WC()->cart->subtotal < $threshold1 ){
        unset( $rates['flat_rate:5'] );
        unset($rates['flat_rate:6']);
    } elseif((WC()->cart->subtotal>$threshold1)and(WC()->cart->subtotal<$threshold2) ) {
        unset( $rates['flat_rate:1'] );
        unset( $rates['flat_rate:6'] ); 
    } elseif((WC()->cart->subtotal > $threshold2) and (WC()->cart->subtotal > $threshold1) ) {
        unset( $rates['flat_rate:1'] );
        unset( $rates['flat_rate:5'] );  
    }
    return $rates;
}

这似乎行得通,但有时(我还没有弄清楚触发器!)它行不通,所有三种运输方式都会出现在购物车中。我想我注意到它只在用户登录时发生,但我对此不是 100% 确定。

如果我的功能是正确的,或者我是否需要更改或改进任何东西,有人可以帮助我吗?

我重新审视了您的代码。您应该尝试以下操作:

add_filter('woocommerce_package_rates','subtotal_based_tiered_shipping', 10, 2 );
function subtotal_based_tiered_shipping( $rates, $package ){
    $threshold1 = 20;
    $threshold2 = 30;
    $subtotal = WC()->cart->subtotal;
    
    if ( $subtotal < $threshold1 ) 
    { // Below 20 ('flat_rate:1' is enabled)
        unset( $rates['flat_rate:5'] );
        unset( $rates['flat_rate:6'] );
    } 
    elseif ( $subtotal >= $threshold1 && $subtotal < $threshold2 ) 
    { // Starting from 20 and below 30 ('flat_rate:5' is enabled)
        unset( $rates['flat_rate:1'] );
        unset( $rates['flat_rate:6'] ); 
    } 
    elseif ( $subtotal >= $threshold2 ) 
    { // Starting from 30 and up ('flat_rate:6' is enabled)
        unset( $rates['flat_rate:1'] );
        unset( $rates['flat_rate:5'] );  
    }
    return $rates;
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。

它现在应该可以正常工作了。

To make it work with "Free shipping" methods too, you will have to disable "Free shipping requires..." option (set to "N/A").


Sometimes you should need to refresh shipping caches:

Once saved this code and emptied cart, go to your shipping settings. In your shipping zone, disable save and re-enable save your shipping methods.