簡體   English   中英

WooCommerce - 根據購物車小計隱藏/顯示運輸方式

[英]WooCommerce - hide / show shipping methods based on cart subtotal

在我的 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;
}

但是代碼沒有效果。 我哪里錯了?

嘗試以下操作(在開頭的代碼中設置 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)。 在運輸區域設置中,禁用/保存任何運輸方式,然后啟用返回/保存。
你已經完成了,你可以測試它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM