WooCommerce - 根据商品总重量向购物车添加额外费用

WooCommerce - Adding Extra fee to Cart based on total items weight

我需要在产品总重量上添加费用并显示在购物车中。
我的意思是在购物车中,添加商品时,我会设置额外费用。

这笔费用应该这样计算:

$extra_charge = $total_cart_weight * 0.15;

如果可能,我该如何实现?

谢谢

我相信你可以使用 this 插件创建一个额外的收费类别。您可能需要编辑插件以使购物车费用的百分比成为总重量费用的百分比,但这应该不难弄清楚。除非我知道你从哪里得到重量,否则我无法真正为你编辑插件。您只需编辑 wc-extra-fee-option.php 文件并更改第 133 行,这样 $extra_fee_option_cost 将乘以权重而不是 $total。您可以通过将权重放在 class 中,然后在第 133 行调用 class 来实现。或者,您可以将权重设置为全局变量,并简单地使用该全局变量代替 $total 在线133. 希望这有帮助!

您可以轻松地将此函数挂接到 woocommerce_cart_calculate_fees 挂钩,这样:

function weight_add_cart_fee() {

    // Set here your percentage
    $percentage = 0.15;

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Get weight of all items in the cart
    $cart_weight = WC()->cart->get_cart_contents_weight();

    // calculate the fee amount
    $fee = $cart_weight * $percentage;

    // If weight amount is not null, adds the fee calcualtion to cart
    if ( !empty( $cart_weight ) ) { 
        WC()->cart->add_fee( __('Extra charge (weight): ', 'your_theme_slug'), $fee, false );
    }
}
add_action( 'woocommerce_cart_calculate_fees','weight_add_cart_fee' );

此代码已经过测试并且有效。它继续在您的活动子主题或主题的 function.php 文件中。

For tax options: see add_fee() method tax options depending on your global tax settings.

参考: