在WooCommerce中排除部分商品参与附加费计算
按商品ID排除PayPal附加费计算的最小改动方案
你只需要在原有函数中添加排除商品ID数组,并遍历购物车计算排除后的有效商品总价,替换原有的小计计算逻辑即可,改动非常小:
修改后的完整代码:
add_action( 'woocommerce_cart_calculate_fees', 'add_checkout_fee_for_gateway' ); function add_checkout_fee_for_gateway() { // Check if we are on the checkout page if ( is_checkout() ) { global $woocommerce; $chosen_gateway = $woocommerce->session->chosen_payment_method; if ( $chosen_gateway == 'paypal' ) { $percentage = 0.09; // 定义需要排除的商品ID数组,自行替换为实际ID $excluded_product_ids = array(123, 456, 789); // 计算排除指定商品后的小计 $subtotal_excluded = 0; foreach ( $woocommerce->cart->get_cart() as $cart_item ) { $product_id = $cart_item['product_id']; // 仅累加不在排除列表中的商品总价 if ( !in_array( $product_id, $excluded_product_ids ) ) { $subtotal_excluded += $cart_item['line_total']; } } $surcharge = $subtotal_excluded * $percentage; $woocommerce->cart->add_fee( '9% value added tax', $surcharge, true, '' ); } } }
关键改动说明:
- 新增
$excluded_product_ids数组:把不需要参与附加费计算的商品ID填进去,多个ID用逗号分隔 - 遍历购物车商品:逐个检查商品ID是否在排除列表外,累加符合条件的商品行总价(
line_total已包含商品数量×单价) - 用筛选后的
$subtotal_excluded替代原有的get_subtotal()计算附加费,其余逻辑完全保留
这样既实现了按商品ID排除的需求,又最大程度保留了原代码的结构,改动量极小。
内容的提问来源于stack exchange,提问作者Paul Vek
相关产品推荐
相关产品推荐

