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

如何累计计算WooCommerce购物车中同附加费分组商品的总附加费

WooCommerce商品附加费按购买数量累加修改方案

1 修正配置项语法错误

你当前配置中用翻译函数__()包裹多商品ID的写法是错误的,__()仅支持字符串参数,存储多商品ID直接使用数组即可,修正后的配置如下:

// Settings
$settings = array(
    array(
        'product_id' => array(123, 456, 789),
        'amount'     => 10,
        'name'       => __( 'Additional service fee', 'woocommerce' ),
    ),
    array(
        'product_id' => array(987, 654, 321),
        'amount'     => 20,
        'name'       => __( 'Additional packing fee', 'woocommerce' ),
    ),
    array(
        'product_id' => array(445, 556, 555),
        'amount'     => 30,
        'name'       => __( 'Additional specific fee', 'woocommerce' ),
    ),
);

注:同时修正了原配置中费用名称的拼写错误

2 修改费用计算逻辑

原代码仅判断分组商品是否存在,存在则仅收取一次费用,需调整为统计对应分组下所有商品的总购买数量,按数量累加计算总费用,修改后的核心计算逻辑如下:

// 遍历所有费用配置分组
foreach ( $settings as $setting ) {
    $group_total_qty = 0;
    // 遍历购物车统计当前分组商品总购买数量
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        // 判断购物车商品是否属于当前分组
        if ( in_array( $cart_item['product_id'], $setting['product_id'] ) ) {
            $group_total_qty += $cart_item['quantity'];
        }
    }
    // 总数量大于0则累加收取费用
    if ( $group_total_qty > 0 ) {
        $total_fee = $setting['amount'] * $group_total_qty;
        WC()->cart->add_fee( $setting['name'], $total_fee );
    }
}

如果你的商品存在多规格变体,需要同时匹配变体ID,可将判断条件修改为:

if ( in_array( $cart_item['product_id'], $setting['product_id'] ) || in_array( $cart_item['variation_id'], $setting['product_id'] ) )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 07:15:02