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

如何合并两个WooCommerce费用动作,仅对指定产品ID收百分比费用

针对指定产品ID收取4%附加费的WooCommerce实现

以下是满足你需求的PHP代码,替换掉原来的两个woocommerce_cart_calculate_fees动作即可:

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

    // 指定需要收取附加费的产品ID
    $target_product_ids = array(652, 645, 625);
    $target_subtotal = 0;
    $percentage = 0.04; // 4% 费率

    // 遍历购物车中的所有商品
    foreach ($cart->get_cart() as $cart_item) {
        $product_id = $cart_item['product_id'];
        // 检查当前商品是否在目标ID列表中
        if (in_array($product_id, $target_product_ids)) {
            // 累加目标商品的小计金额(单价×数量)
            $target_subtotal += $cart_item['line_total'];
        }
    }

    // 如果目标商品总金额大于0,计算并添加附加费
    if ($target_subtotal > 0) {
        $fee_amount = $target_subtotal * $percentage;
        $cart->add_fee('指定产品附加费(4%)', $fee_amount, false);
    }
}

代码说明:

  • 仅对ID为652、645、625的产品收取附加费,其他商品不受影响
  • 附加费基于目标商品的小计金额计算4%的费用
  • add_fee函数第三个参数设为false表示附加费不含税,若需要含税可改为true
  • 后台管理页面不会触发该逻辑,仅在前端购物车/结算页生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 19:10:59