WooCommerce使用doublediscount优惠券为促销商品叠加双倍折扣(上限15%)
WooCommerce 促销商品双倍折扣优惠券实现方案
完整调整后代码
add_action( 'woocommerce_before_calculate_totals', 'double_saleprice_coupon' ); function double_saleprice_coupon( $cart ) { if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; $coupon_id = 'doublediscount'; // 校验购物车是否已应用目标优惠券,未应用直接终止逻辑 $applied_coupons = $cart->get_applied_coupons(); if ( !in_array( $coupon_id, $applied_coupons ) ) { return; } // 遍历购物车商品 foreach ( $cart->get_cart() as $cart_item_key => $cart_item ){ $product = $cart_item['data']; // 跳过非促销商品 if ( !$product->is_on_sale() ) { continue; } // 跳过捆绑商品(兼容WooCommerce Product Bundles插件,无该插件可删除此行判断) if ( function_exists('wc_pb_is_bundled_cart_item') && wc_pb_is_bundled_cart_item($cart_item) === true ) { continue; } $regular_price = $product->get_regular_price(); $sale_price = $product->get_sale_price(); $original_discount_amount = $regular_price - $sale_price; $original_discount_percent = round( $original_discount_amount / $regular_price * 100, 0 ); // 计算额外叠加折扣,最高不超过15% $extra_discount_percent = min( $original_discount_percent, 15 ); // 计算总折扣比例和最终结算价格 $total_discount_percent = $original_discount_percent + $extra_discount_percent; $final_price = $regular_price * ( 100 - $total_discount_percent ) / 100; // 更新购物车商品的结算价格 $product->set_price( $final_price ); } }
核心修改说明
- 新增优惠券生效判断:只有用户应用了
doublediscount优惠券时,才会触发折扣叠加逻辑 - 严格匹配折扣规则:额外叠加折扣取「原有促销折扣」和「15%」的较小值,符合上限要求
- 新增价格写入逻辑:通过WooCommerce原生
set_price()方法直接更新购物车商品的结算价格,是官方推荐的修改方式 - 新增函数存在性校验:避免未安装WooCommerce Product Bundles插件时调用对应函数出现报错
- 移除了调试用的
echo输出,避免页面出现异常内容
配置注意事项
doublediscount优惠券本身的折扣类型请设置为「固定购物车折扣」,折扣金额填0即可,仅作为触发叠加逻辑的标识使用。如果不需要排除捆绑商品,直接删除对应判断行即可。
内容的提问来源于stack exchange,提问作者Cray
相关产品推荐
相关产品推荐

