【问题标题】:Tiered Shipping based on cart subtotal in Woocommerce基于 Woocommerce 中的购物车小计的分层运输
【发布时间】:2018-01-26 06:48:32
【问题描述】:

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

  • 如果价格低于 20 欧元,运费为 5.90 欧元,
  • 如果价格从 20 欧元开始且低于 30 欧元,则运费为 4.90 欧元
  • 如果价格从 30 欧元开始,运费为 3,90 欧元。

我有非常基本的PHP知识,并且修改了我找到的一个代码sn-p。

这是我的代码:

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】:

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

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

它现在应该可以按预期工作了。

要使其也适用于“免费送货”方法,您必须禁用 “免费送货需要...” 选项(设置为 “不适用”)


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

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

【讨论】:

  • 感谢您的帮助和代码的详细信息。对学习PHP很有帮助。
猜你喜欢
  • 2021-08-21
  • 2020-12-02
  • 2019-01-23
  • 2018-01-30
  • 1970-01-01
  • 1970-01-01
  • 2016-10-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多