简体   繁体   English

Woocommerce 中的渐进式购物车项目自定义运费

[英]Progressive cart item custom shipping cost in Woocommerce

I need to figure out a way to do woocommerce shipping rates based on items on cart.我需要想办法根据购物车上的物品来计算 woocommerce 运费。 I need to charge 120 if buying 1-2 items and 180 buying 3. I added a free shipping option for 4+ (based on $)买 1-2 件需要 120,买 3 件需要 180。我添加了 4+ 的免费送货选项(基于 $)

I tried adding this to the flat rate price: 120+60([qty]-2) it works in all instances but the 1 item, because it charges $60.我尝试将其添加到统一费率价格中:120+60([qty]-2) 它适用于所有情况,但 1 件商品除外,因为它收费 60 美元。

Any thoughts?有什么想法吗?

With the following code, you will be able to get this shipping rates:使用以下代码,您将能够获得此运费:
- 1 or 2 items: $120 - 1 或 2 件:120 美元
- 3 items: $180 - 3 件:180 美元
- 4 items or more: Free shipping (hiding flat rate method) - 4 件或更多:免运费(隐藏统一费率方法)

1) Add the following code to function.php file of your active child theme (active theme): 1)将以下代码添加到您的活动子主题(活动主题)的function.php文件中:

add_filter('woocommerce_package_rates', 'custom_progressive_shipping_costs', 10, 2);
function custom_progressive_shipping_costs( $rates, $package ){

    $items_count  = WC()->cart->get_cart_contents_count();

    if( $items_count < 3 ){
        $cost_rate = 2;
    } else {
        $cost_rate = $items_count;
    }

    foreach ( $rates as $rate_key => $rate ){
        $taxes = [];
        $has_taxes = false;
        // Targeting "flat rate"
        if ( 'flat_rate' === $rate->method_id ) {
            // For 1, 2 or 3 items
            if ( $items_count <= 3 ) {
                $rates[$rate_key]->cost = $rate->cost * $cost_rate;

                // Taxes rate cost (if enabled)
                foreach ($rates[$rate_key]->taxes as $key => $tax){
                    if( $tax > 0 ){
                        $has_taxes = true;
                        $taxes[$key] = $tax * $cost_rate;
                    }
                }
                if( $has_taxes )
                    $rates[$rate_key]->taxes = $taxes;
            }
            // For more than 3 hide Flat rate
            else {
                // remove flat rate method
                unset($rates[$rate_key]);
            }
        }
    }
    return $rates;
}

And save…并保存…

2) In Your shipping method settings, you will need to set 60 as your "Flat rate" cost and SAVE. 2) 在您的运输方式设置中,您需要将60设置为“统一费率”成本并保存。

You need to keep your minimal amount for "Free shipping" method.您需要保留“免费送货”方法的最低金额。

You are done.你完成了。 Tested and works.测试和工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM