WooCommerce按购物车小计自动应用优惠券排除特定商品问题咨询
配置未生效的核心原因
- 你编写的自定义代码完全绕过了WooCommerce优惠券的原生校验逻辑:后台勾选的「排除促销商品」规则仅会在优惠券原生的可用性判断环节生效,你硬编码直接读取购物车全量小计
WC()->cart->get_subtotal()做满减判断,既没有过滤促销商品金额,也没有读取优惠券的配置规则,因此后台配置不会作用于你写的逻辑。 - 原代码末尾重复调用了
wc_clear_notices(),会直接清空你前面输出的优惠提示,这也是隐藏的功能异常点。
实现需求的修复代码
你可以直接替换原有代码,新代码会自动排除促销商品的金额来计算是否满足100美元的最低消费门槛,同时兼容后台优惠券的「排除促销商品」配置:
add_action( 'woocommerce_checkout_before_order_review' , 'add_coupon_notice' ); function add_coupon_notice() { $minimum_amount = 100; $valid_total = 0; // 仅累加非促销商品的金额作为门槛判断依据 foreach ( WC()->cart->get_cart() as $cart_item ) { $product = $cart_item['data']; if ( ! $product->is_on_sale() ) { $valid_total += $cart_item['line_subtotal']; } } wc_clear_notices(); $coupon_code = '20OFF100'; if ( $valid_total < $minimum_amount ) { WC()->cart->remove_coupon( $coupon_code ); wc_print_notice( "Get 20% off if you spend more than $".$minimum_amount." on non-sale items", 'notice' ); } else { WC()->cart->apply_coupon( $coupon_code ); wc_print_notice( '20% off $100 or more on non-sale items - Discount Applied!', 'notice' ); } }
额外说明
- 请保持后台优惠券的「排除促销商品」勾选状态,这样优惠券应用后也只会对非促销商品生效,和门槛统计逻辑保持一致。
- 如果你需要排除指定的某几个特定商品而非所有促销商品,可以在遍历购物车的逻辑中新增商品ID判断,过滤你不需要统计的商品即可。
内容的提问来源于stack exchange,提问作者Matt Melton
相关产品推荐
相关产品推荐

