php – 在Woocommerce中为每3件物品的统一运费添加额外费用

我正在经营一家woocommerce商店,并使用统一运费15美元.我写了一个公式,为每个额外的项目增加1.25美元.

13.50 + ( 1.25 * [qty])

啜饮“统一费率设置|额外每件物品1.25美元:

php  – 在Woocommerce中为每3件物品的统一运费添加额外费用

但我想为每3件物品增加1.25美元.我的意思是3,6,9,12等……

谁能告诉我怎么做?任何帮助表示赞赏.

解决方法:

以下代码将为每3件商品(3,6,9 ……)增加额外费用.

您需要使用简单的初始费用而不是公式来更改运费.

You may have to “Enable debug mode” in general shipping settings under “Shipping options” tab, to disable temporarily shipping caches.

代码(您将在其中设置额外的运费):

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

    // HERE set your additional shipping cost
    $additional_cost = 1.25;
    $items_count = WC()->cart->get_cart_contents_count();

    // 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;
            // Adding to cost the additional cost each 3 items (3, 6, 9 …)
            for($i = 0; $i <= $items_count; $i+=3){
                $new_cost += $additional_cost;
            }
            // 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文件中.经过测试和工作.

Don’t forget to disable “Enable debug mode” option in shipping settings.

根据您的第二条评论回答:

你将替换这个块:

// Adding to cost the additional cost each 3 items (3, 6, 9 …)
for($i = 0; $i <= $items_count; $i+=3){
    $new_cost += $additional_cost;
}

通过以下方式:

// Adding to cost an additional fixed cost for the 2nd item
if($items_count >= 2){
    $new_cost += 6.21; 
}

// Adding to cost the additional cost each 3 items (3, 6, 9 …)
for($i = 0; $i <= $items_count; $i+=3){
    $new_cost += $additional_cost;
}
上一篇:work_42_OSS?


下一篇:OSS使用