在WooCommerce中设置根据购物车总重量计算的自定义运费费用

时间:2017-08-05 13:04:28

标签: php wordpress woocommerce cart shipping

在Woocommerce中,我已经安装了一个装运插件,但它计算了购物车中每件商品的运费,而不是每个订单总数。

我需要的是以这种方式计算运费: - 第一公斤是5美元 - 所有其他人每公斤1美元。

有可能吗?

如果购物车中有2件物品每件1公斤,则使用该插件,它计算出的运费为2 x $ 5 = $ 10
相反,我需要的是: $ 5 (第一公斤) + $ 1 (额外公斤) = $ 6 (2公斤)

我没有来自插件开发者的回复,所以寻找解决方法。

1 个答案:

答案 0 :(得分:1)

  

更新:您不需要任何插件(因此您可以删除它)

要获得按购物车总重量计算的运费,请:

  • 初始金额$ 5(第一公斤)
  • 每增加一公斤的可变利率为$ 1

执行以下操作:

1)WooCommerce中的设置:
对于您的所有“统一费率”送货方式(在每个送货区域中),设置 1 的费用(以千克为单位)

enter image description here

所以费用

  

(完成禁用/保存并启用/保存以刷新woocommerce瞬态缓存)

2)自定义代码 (因为运费单位成本为1美元/公斤,我们在计算中将总公斤重量加4公斤以设置正确的成本)

add_filter( 'woocommerce_package_rates', 'custom_delivery_flat_rate_cost_calculation', 10, 2 );
function custom_delivery_flat_rate_cost_calculation( $rates, $package )
{
    // The total cart items  weight
    $cart_weight = WC()->cart->get_cart_contents_weight();

    foreach($rates as $rate_key => $rate_values){
        $method_id = $rate_values->method_id;
        $rate_id = $rate_values->id;
        if ( 'flat_rate' === $method_id ) {
            ##  SHIPPING COSTS AND TAXES CALCULATIONS ##
            $rates[$rate_id]->cost = $rates[$rate_id]->cost*($cart_weight+4);
            foreach ($rates[$rate_id]->taxes as $key => $tax){
                if( $rates[$rate_id]->taxes[$key] > 0 ){
                    $tax_cost = number_format( $rates[$rate_id]->taxes[$key]*($cart_weight+4));
                    $rates[$rate_id]->taxes[$key] = $tax_cost;
                }
            }
        }
    }
    return $rates;
}

代码放在活动子主题(或主题)的function.php文件中,或者放在任何插件文件中。

此代码已经过测试,适用于woocommerce版本2.6.x和3 +

相关问题