如何实现基于购物车重量的标准优惠券折扣功能?
基于购物车重量的常规WooCommerce优惠券实现方案
核心思路
通过WooCommerce的钩子拦截优惠券的折扣计算逻辑,替换为基于购物车重量的自定义规则,把临时的「0元券+添加费用」方案改成标准优惠券形式,用户可直接在后台管理优惠券。
具体实现步骤
后台创建常规优惠券
在WooCommerce后台创建一张优惠券,自定义优惠券代码(比如WEIGHT_DISCOUNT),折扣类型选「固定折扣」或「百分比折扣」均可(建议把默认折扣金额设为0,避免和自定义逻辑冲突)。添加自定义代码
将以下代码添加到主题的functions.php文件或自定义插件中:
add_filter('woocommerce_coupon_get_discount_amount', 'weight_based_coupon_calculation', 10, 5); function weight_based_coupon_calculation($discount, $price_to_discount, $cart_item, $single, $coupon) { // 替换为你创建的优惠券代码 $target_coupon_code = 'WEIGHT_DISCOUNT'; // 仅对指定优惠券生效 if ($coupon->get_code() !== $target_coupon_code) { return $discount; } // 获取购物车总重量(单位与后台设置一致,如kg) $cart_total_weight = WC()->cart->get_cart_contents_weight(); // -------------------------- // 自定义折扣规则,按需修改 // -------------------------- // 示例1:每1kg减2元,最低折扣0 $discount_per_kg = 2; $calculated_discount = $cart_total_weight * $discount_per_kg; // 示例2:阶梯折扣 // if ($cart_total_weight <= 5) { // $calculated_discount = 5; // } elseif ($cart_total_weight <= 10) { // $calculated_discount = 12; // } else { // $calculated_discount = 20; // } // 示例3:重量满8kg打9折(后台优惠券类型设为百分比) // if ($cart_total_weight >= 8) { // $calculated_discount = WC()->cart->get_subtotal() * 0.1; // } else { // $calculated_discount = 0; // } // 处理单品折扣场景(优惠券应用到单个商品时) if ($single && $cart_item) { $item_total_weight = $cart_item['data']->get_weight() * $cart_item['quantity']; $weight_ratio = $item_total_weight / $cart_total_weight; $discount = $calculated_discount * $weight_ratio; } else { // 购物车整体折扣 $discount = $calculated_discount; } // 确保折扣不为负数 return max($discount, 0); }
代码说明
woocommerce_coupon_get_discount_amount钩子会在计算优惠券折扣时触发,用于替换默认计算逻辑- 通过判断优惠券代码,避免影响其他正常优惠券
- 可根据需求修改折扣规则,支持按重量比例减、阶梯折扣、满重打折等多种形式
- 兼容单品折扣和购物车整体折扣两种场景,确保逻辑覆盖全面
注意事项
- 确保所有商品都正确设置了重量,否则
get_cart_contents_weight会返回0,导致折扣失效 - 后台优惠券的使用限制(如最低消费、适用分类)可正常生效,不影响自定义折扣逻辑
- 可在优惠券的「描述」字段添加折扣说明,用户在购物车页面能直观看到规则
内容的提问来源于stack exchange,提问作者go-diego-go
相关产品推荐
相关产品推荐

