WooCommerce如何实现仅首件gallon属性产品可用test123优惠券享10%折扣
WooCommerce首件gallon属性商品专属折扣实现方案
原有代码存在的问题
- 仅修改了前端购物车商品小计的展示样式,没有修改购物车底层计算逻辑,实际结账时仍会按原价计算
- 没有设置折扣应用标记,所有带gallon属性的商品都会触发折扣,不符合仅首件生效的要求
修正后完整代码
// 实际修改购物车商品价格,保证结账金额正确 add_action( 'woocommerce_before_calculate_totals', 'apply_first_gallon_discount', 10, 1 ); function apply_first_gallon_discount( $cart ) { // 跳过后台非AJAX请求 if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; $coupon_code = 'test123'; // 优惠券未使用则不生效 if ( ! $cart->has_discount( $coupon_code ) ) return; $discount_applied = false; // 标记折扣是否已应用到首件商品 foreach ( $cart->get_cart() as $cart_item ) { $gallon_attr = $cart_item['data']->get_attribute( 'pa_size' ); // 仅给第一个符合条件的gallon商品打9折 if ( $gallon_attr === 'Gallon' && ! $discount_applied ) { $original_price = $cart_item['data']->get_regular_price(); $cart_item['data']->set_price( $original_price * 0.9 ); $discount_applied = true; break; // 应用后直接跳出循环,后续商品不再判断 } } } // 前端展示原价划掉+折扣价的样式 add_filter( 'woocommerce_cart_item_subtotal', 'show_gallon_discount_subtotal', 99, 3 ); function show_gallon_discount_subtotal( $subtotal, $cart_item, $cart_item_key ) { global $woocommerce; $coupon_code = 'test123'; $gallon_attr = $cart_item['data']->get_attribute( 'pa_size' ); static $discount_shown = false; // 静态变量标记前端展示是否已处理 if ( $woocommerce->cart->has_discount( $coupon_code ) && $gallon_attr === 'Gallon' && ! $discount_shown ) { $original_subtotal = wc_price( $cart_item['data']->get_regular_price() * $cart_item['quantity'] ); $discounted_subtotal = wc_price( $cart_item['data']->get_price() * $cart_item['quantity'] ); $subtotal = sprintf( '<s>%s</s> %s', $original_subtotal, $discounted_subtotal ); $discount_shown = true; } return $subtotal; }
实现逻辑说明
- 通过
woocommerce_before_calculate_totals钩子在购物车总额计算前修改商品价格,是实际生效的核心逻辑 - 用
$discount_applied标记位控制仅第一个匹配gallon属性的商品应用折扣,后续同类商品全部跳过 - 前端展示逻辑通过静态变量和计算逻辑对齐,仅第一个打折商品会显示划掉的原价样式
- 若需要限制哪怕首件商品购买多件也仅1件享受折扣,可以调整价格计算逻辑拆分数量处理,当前代码按「首个gallon商品项全部享受折扣」的需求实现
内容的提问来源于stack exchange,提问作者Patrick Nelson
相关产品推荐
相关产品推荐

