如何获取使用优惠券后的WooCommerce购物车小计?
解决WooCommerce扣除优惠券折扣后计算免运费门槛的问题
你之前的代码无效是因为WC()->cart->discounts是WooCommerce的折扣对象,不是直接可用于计算的数值,无法直接做减法运算。
以下是两种可行的解决方案:
方案1:仅扣除优惠券总折扣
适合只需要从原始购物车小计中减去优惠券折扣的场景:
// 获取未扣除任何折扣的购物车原始小计 $original_subtotal = WC()->cart->subtotal; // 获取所有优惠券的总折扣金额 $total_coupon_discount = WC()->cart->get_discount_total(); // 计算扣除优惠券折扣后的金额 $amount_after_discount = $original_subtotal - $total_coupon_discount; // 如需格式化显示金额,可使用WooCommerce内置函数 echo wc_price($amount_after_discount);
方案2:扣除商品折扣+优惠券折扣的最终金额
如果免运费规则需要同时考虑商品自身折扣(比如商品自带打折)和优惠券折扣,可用这个逻辑:
// 获取已经扣除商品级折扣后的小计(已减去商品本身的优惠) $subtotal_after_item_discounts = WC()->cart->get_subtotal(); // 获取优惠券带来的总折扣金额 $coupon_total_discount = WC()->cart->get_discount_total(); // 计算最终扣除所有折扣后的金额 $final_calculated_amount = $subtotal_after_item_discounts - $coupon_total_discount;
注意事项
- 确保代码在WooCommerce购物车数据初始化完成后运行,比如挂在
woocommerce_cart_calculate_fees或woocommerce_before_cart_totals钩子上,避免因数据未加载导致计算错误。 - 如果涉及税费,可根据需求结合
WC()->cart->subtotal_tax等属性调整计算逻辑。
内容的提问来源于stack exchange,提问作者brun299
相关产品推荐
相关产品推荐

