You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WooCommerce中代码添加的附加费未被征税问题求助

问题解决:WooCommerce附加费计入税费的修复方案

核心问题原因

你代码中调用$cart->add_fee()时第三个参数传了false,这个参数控制费用是否需要计税,设为false会直接让附加费被排除在税费计算范围之外。

修复后的代码

把两个add_fee的第三个参数改为true,同时优化重复的重量计算逻辑,让代码更简洁高效:

add_action( 'woocommerce_cart_calculate_fees', 'shipping_weight_fee', 30, 1 );
function shipping_weight_fee( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // 统一转换购物车重量为克(避免重复计算)
    $cart_weight = $cart->get_cart_contents_weight() * 1000;

    // 计算能源附加费
    $energy_fee = 0.00697; // 1000g以下基础费用
    if( $cart_weight > 1000 ){
        // 计算超出部分的额外费用,每1000g加0.00697
        $extra_kg = ceil( ($cart_weight - 1000) / 1000 );
        $energy_fee += $extra_kg * 0.00697;
    }
    // 标记为需计税(第三个参数设为true)
    $cart->add_fee( __( 'Energy Surcharge' ), $energy_fee, true );

    // 计算环境附加费
    $env_fee = 0.00165; // 1000g以下基础费用
    if( $cart_weight > 1000 ){
        $extra_kg = ceil( ($cart_weight - 1000) / 1000 );
        $env_fee += $extra_kg * 0.00165;
    }
    // 标记为需计税
    $cart->add_fee( __( 'Environmental Surcharge' ), $env_fee, true );
}

关键说明

  • $cart->add_fee( $name, $amount, $taxable, $class )的第三个参数$taxable设为true后,WooCommerce会自动将该费用纳入税费计算范围,和商品、运费一起计税。
  • 用ceil()替代原有的循环逻辑,直接计算超出基础重量的份数,代码执行效率更高,逻辑更清晰。

内容的提问来源于stack exchange,提问作者Sam Smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 07:31:06