WooCommerce-基于购物车小计的隐藏/显示运输方式

时间:2020-07-08 16:28:01

标签: php woocommerce shipping-method

在我的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 个答案:

答案 0 :(得分:1)

尝试以下(在代码的开头设置您的5种送货方式对ID进行评分)。另外,对于您的“免费送货”费率,请将“最低订单金额”设置为 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)。此代码已保存在您的function.php文件中。
2)。在运送区域设置中,禁用/保存任何运送方法,然后启用返回/保存。
您已完成,您可以对其进行测试。