如何合并两个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
相关产品推荐
相关产品推荐

