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

WooCommerce购物车特定产品加附加费仅首个产品生效问题求助

问题原因

你的代码核心问题是调用WC()->cart->add_fee()时使用了固定的相同名称,WooCommerce中同名附加费会直接覆盖旧值,不会累加,因此循环匹配到多个符合条件的产品时,后续的附加费会把前面的覆盖,最终仅能看到生效一个。
另外你代码中存在变量名拼写错误:$quantiy应为$quantity,虽然不触发致命错误,但属于不规范写法。

修复方案

你可以根据业务需求选择以下两种实现方式:

方案1:累计总金额后统一添加附加费

适合所有符合规则的产品附加费合并成一条展示在购物车/结账页,是最常用的实现方式:

/* 给指定产品添加附加费 */ 
add_action('woocommerce_cart_calculate_fees', 'statie_geld'); 
function statie_geld() { 
   if (is_admin() && !defined('DOING_AJAX')) {return;}
   // 初始化总附加费金额
   $total_statiegeld = 0;
   foreach( WC()->cart->get_cart() as $item_keys => $item ) {
     $quantity = $item['quantity'];
     if( in_array( $item['product_id'], statiegeld_ids() )) { 
        $total_statiegeld += 3.60 * $quantity; 
     } 
   }
   // 金额大于0才添加附加费,避免无符合产品时展示0元附加费
   if ($total_statiegeld > 0) {
       WC()->cart->add_fee(__('Statiegeld Petfles 24'), $total_statiegeld );
   }
} 
function statiegeld_ids() { 
   return array( 4535, 4537, 89694, 89706, 3223, 4742, 14846, 26972, 32925, 32927, 32929, 37475 ); 
}

方案2:每个产品单独添加附加费

如果需要每个符合条件的产品的附加费单独展示,可以给每个附加费名称加上唯一标识,避免同名覆盖:

/* 给指定产品添加附加费 */ 
add_action('woocommerce_cart_calculate_fees', 'statie_geld'); 
function statie_geld() { 
   if (is_admin() && !defined('DOING_AJAX')) {return;} 
   foreach( WC()->cart->get_cart() as $item_keys => $item ) {
     $quantity = $item['quantity'];
     if( in_array( $item['product_id'], statiegeld_ids() )) { 
        // 附加费名称加上产品ID保证唯一
        $fee_name = sprintf(__('Statiegeld Petfles 24 (产品ID: %s)'), $item['product_id']);
        WC()->cart->add_fee($fee_name, 3.60 * $quantity ); 
     } 
   } 
} 
function statiegeld_ids() { 
   return array( 4535, 4537, 89694, 89706, 3223, 4742, 14846, 26972, 32925, 32927, 32929, 37475 ); 
}

内容的提问来源于stack exchange,提问作者Erik Duits

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 09:27:01