WooCommerce优惠券:按数量为低价商品阶梯折扣实现问题
修复WooCommerce优惠券多件商品折扣规则的问题
原代码仅能给单件最低价格商品应用折扣,无法满足“每2件就有1件低价商品享40%折扣,4件则2件低价商品享折扣”的需求,以下是修正后的代码:
add_filter( 'woocommerce_coupon_get_discount_amount', 'filter_wc_coupon_get_discount_amount', 10, 5 ); function filter_wc_coupon_get_discount_amount( $discount_amount, $discounting_amount, $cart_item, $single, $coupon ) { // 指定优惠券代码,替换成你实际用的 $coupon_code = 'coupon_code'; // 只对指定优惠券生效 if( strtolower( $coupon_code ) !== strtolower( $coupon->get_code() ) ) return $discount_amount; $items_prices = []; $total_items = 0; // 遍历购物车,把每件商品(包括多数量的单品拆分)的价格和key存起来 foreach( WC()->cart->get_cart() as $key => $item ){ if ( wc_prices_include_tax() ) { $price = wc_get_price_including_tax( $item['data'] ); } else { $price = wc_get_price_excluding_tax( $item['data'] ); } if ( $price > 0 ){ // 比如一个商品买3件,就拆成3条记录,保证每件都参与排序 for( $i = 0; $i < $item['quantity']; $i++ ){ $items_prices[] = [ 'key' => $key, 'price' => $price ]; $total_items++; } } } // 商品总数大于1才处理折扣 if ( $total_items > 1 ) { // 计算能享折扣的商品数量:每2件有1件可折扣 $discountable_count = floor( $total_items / 2 ); if ( $discountable_count <= 0 ) { return $discount_amount; } // 按价格从低到高排序所有商品 usort( $items_prices, function( $a, $b ) { return $a['price'] - $b['price']; }); // 提取前N件低价商品的key(N是可折扣数量) $discountable_keys = []; for( $i = 0; $i < $discountable_count; $i++ ){ $discountable_keys[] = $items_prices[$i]['key']; } // 当前商品在可折扣列表里的话,返回40%的折扣金额 if ( in_array( $cart_item['key'], $discountable_keys ) ) { $item_price = wc_prices_include_tax() ? wc_get_price_including_tax( $cart_item['data'] ) : wc_get_price_excluding_tax( $cart_item['data'] ); return $item_price * 0.4; } } // 不符合条件就返回0 return 0; }
关键改动说明
- 拆分多数量商品:把单个商品的多件数量拆成独立条目,避免同一件商品买多件时只算一次价格的问题,确保排序准确。
- 动态计算可折扣数量:用
floor($total_items / 2)自动计算能享折扣的商品数,比如4件对应2件折扣,3件对应1件折扣。 - 精准筛选低价商品:将所有商品按价格从低到高排序,取前N件作为折扣对象,完全符合“折扣应用于价值较低商品”的需求。
- 明确折扣金额计算:直接按商品价格的40%计算折扣,确保折扣力度正确。
注意事项
- 把代码里的
'coupon_code'替换成你实际使用的优惠券代码。 - 测试时可以分别加入2件、3件、4件商品,验证折扣是否正确应用到低价商品上。
- 如果要调整折扣比例,把
0.4改成对应数值即可(比如30%折扣就写0.3)。
内容的提问来源于stack exchange,提问作者xtianfab
相关产品推荐
相关产品推荐

