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

问题描述 投票:2回答:1

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

  • 如果价格低于20€,运费为5,90€,
  • 如果价格从20欧元起低于30欧元,则运费为4,90欧元
  • 如果价格从30欧元起,则运费为3,90欧元。

我有非常基本的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%肯定。

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

php wordpress woocommerce cart shipping
1个回答
1
投票

我稍微重新审视了你的代码。您应该尝试以下方法:

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文件中。

它应该按预期工作。

要使其与“免运费”方法一起使用,您必须禁用“免运费要求...”选项(设置为“N / A”)。


有时您需要刷新运输缓存:

保存此代码并清空购物车后,请转到您的送货设置。在您的送货区域中,禁用保存并重新启用保存送货方式。

© www.soinside.com 2019 - 2024. All rights reserved.