簡體   English   中英

運輸成本基於Woocommerce 3中的購物車總重量

[英]Shipping cost based on cart total weight in Woocommerce 3

在我的Woocommerce網上商店中,我確實有不同的產品。 我想按購物車總重量計算運費:

  • 06公斤的費用是5 €
  • 612公斤的成本是9 €

實際上,如果我的產品為1公斤,則運費為5 € ,但如果我在購物籃中有10件該產品,則運費仍為5 € (應改為9 €

如何根據購物車總重量計算累進運費?

嘗試以下功能,“平均費用”將根據購物車的總重量而改變。

使用“費率”運輸方法,您需要使用簡單的初始成本而不是任何公式來設置參考運輸成本。 例如可以是1 這筆費用將根據購物車總重量動態地由我的答案代碼代替。

您可能必須在“ 運送選項 ”標簽下的常規運送設置中啟用啟用調試模式 ”, 才能暫時禁用運送緩存。

add_filter('woocommerce_package_rates', 'shipping_cost_based_on_weight', 12, 2);
function shipping_cost_based_on_weight( $rates, $package ){
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return $rates;

    // HERE define the differents costs
    $cost1 = 5; // Up to 6 Kg
    $cost2 = 9; // Above 6 Kg and below 12 kg
    $cost3 = 9; // Above 12 kg

    // The cart total Weight
    $total_weight = WC()->cart->get_cart_contents_weight();

    // Loop through the shipping taxes array
    foreach ( $rates as $rate_key => $rate ){
        $has_taxes = false;
        // Targetting "flat rate"
        if( 'flat_rate' === $rate->method_id ){
            // Get the initial cost
            $initial_cost = $new_cost = $rates[$rate_key]->cost;

            // Calculate new cost
            if( $total_weight <= 6 ) { // Below 6 Kg
                $new_cost = $cost1;
            }
            elseif( $total_weight > 6 && $total_weight <= 12 ) { // Between 6 and 12 Kg
                $new_cost = $cost2;
            }
            else { // Above 12 Kg
                $new_cost = $cost3;
            }

            // Set the new cost
            $rates[$rate_key]->cost = $new_cost;

            // Taxes rate cost (if enabled)
            $taxes = [];
            // Loop through the shipping taxes array (as they can be many)
            foreach ($rates[$rate_key]->taxes as $key => $tax){
                if( $rates[$rate_key]->taxes[$key] > 0 ){
                    // Get the initial tax cost
                    $initial_tax_cost = $new_tax_cost = $rates[$rate_key]->taxes[$key];
                    // Get the tax rate conversion
                    $tax_rate    = $initial_tax_cost / $initial_cost;
                    // Set the new tax cost
                    $taxes[$key] = $new_cost * $tax_rate;
                    $has_taxes   = true; // Enabling tax
                }
            }
            if( $has_taxes )
                $rates[$rate_key]->taxes = $taxes;
        }
    }
    return $rates;
}

代碼進入您的活動子主題(或活動主題)的function.php文件中。 經過測試和工作。

一旦測試,別忘了在出廠設置中禁用“啟用調試模式”選項。

暫無
暫無

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

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