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


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

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

这个费用应该这样计算:

$extra_charge = $total_cart_weight * 0.15;

如果可能的话,我该怎么做?

谢谢

您可以轻松地将此函数与 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文件上运行。

关于税务选项:参见add_fee()方法税务选项取决于您的全局税务设置。

参考:

    类WC_Cart - add_fee()方法
  • 以编程方式向WooCommerce购物车添加免税费用
  • WooCommerce -制作一组优惠券,为订单增加固定费用

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