提问者:小点点

WooCommerce-基于购物车小计隐藏/显示配送方式


在我的WooCommerce商店(使用版本4.2.2),我想隐藏/显示一些基于购物车小计的发货方法,如下所示:

  • 低于25欧元:仅显示装运方式A和B,
  • 25至49欧元:仅显示装运方式C和D,
  • 50欧元或以上:仅显示免费送货

注:装运方式A、B、C和D均为“统一费率”。

我已经谷歌了这个,并设法让这个尝试以下代码(我只是测试一个速率和一个阈值):

add_filter( 'woocommerce_package_rates', 'hide_shipping', 10, 2 );
function hide_shipping( $rates, $package ) {
    // Retrieve cart subtotal
    global $woocommerce;
    $cart_subtotal = $woocommerce->cart->get_subtotal();
 
    if( $cart_subtotal > 25 ){
        unset( $rates['flat_rate:7'] );
    }
 
    return $rates;
}

但该守则没有任何效力。我哪里做错了?


共1个答案

匿名用户

尝试以下操作(在开始时在代码中设置您的5种运输方式费率Ids)。另外,对于您的免费送货率,将最小订单金额设置为0(0)。

add_filter( 'woocommerce_package_rates', 'hide_specific_shipping_method', 10, 2 );
function hide_specific_shipping_method( $rates, $package ) {
    // Settings: define you shipping rate IDs below
    $rate_id_1     = 'flat_rate:7';
    $rate_id_2     = 'flat_rate:11';
    $rate_id_3     = 'flat_rate:12';
    $rate_id_4     = 'flat_rate:15';
    $rate_free     = 'free_shipping:5';
    
    $cart_subtotal = WC()->cart->get_subtotal();
    
    if ( $cart_subtotal < 25 ) {
        // Enable only methods 1 et 2
        if ( isset($rates[$rate_id_3]) )
             unset( $rates[$rate_id_3] );
        if ( isset($rates[$rate_id_4]) )
             unset( $rates[$rate_id_4] );
        if ( isset($rates[$rate_free]) )
             unset( $rates[$rate_free] );
    } 
    elseif ( $cart_subtotal >= 25 && $cart_subtotal < 50 ) {
        // Enable only methods 3 et 4
        if ( isset($rates[$rate_id_1]) )
             unset( $rates[$rate_id_1] );
        if ( isset($rates[$rate_id_2]) )
             unset( $rates[$rate_id_2] );
        if ( isset($rates[$rate_free]) )
             unset( $rates[$rate_free] );
    } 
    else {
        // Enable only Free shipping
        if ( isset($rates[$rate_id_1]) )
             unset( $rates[$rate_id_1] );
        if ( isset($rates[$rate_id_2]) )
             unset( $rates[$rate_id_2] );
        if ( isset($rates[$rate_id_3]) )
             unset( $rates[$rate_id_3] );
        if ( isset($rates[$rate_id_4]) )
             unset( $rates[$rate_id_4] );
    }
    return $rates;
}

代码functions.php活动子主题(或活动主题)的文件中。测试和工作。

重要提示:刷新装运缓存:
1)。此代码已保存在函数中。php文件
2)。在配送区域设置中,禁用/保存任何配送方法,然后启用“返回/保存”
您完成了,您可以测试它