WooCommerce结账强制使用优惠券:现有代码失效无法进入结账页求助
WooCommerce 强制Redeem分类商品结账需使用有效优惠券
原代码问题分析
你的代码存在两个核心问题:
- 硬编码固定优惠券
0001,无法满足「任意有效优惠券」的需求 - 仅检查指定优惠券是否存在,未验证优惠券是否对当前购物车商品有效,同时错误提示逻辑可能干扰结账页加载
修正后的代码
将以下代码添加到你的主题functions.php文件或自定义插件中:
add_action( 'woocommerce_check_cart_items', 'mandatory_valid_coupon_for_redeem_category' ); function mandatory_valid_coupon_for_redeem_category() { // 目标商品分类slug $target_category = 'redeem'; $has_redeem_product = false; $has_valid_coupon = false; // 检查购物车中是否包含Redeem分类的商品 foreach ( WC()->cart->get_cart() as $cart_item ) { if ( has_term( $target_category, 'product_cat', $cart_item['product_id'] ) ) { $has_redeem_product = true; break; } } // 如果购物车有Redeem商品,检查是否有有效优惠券 if ( $has_redeem_product ) { $applied_coupons = WC()->cart->get_applied_coupons(); if ( ! empty( $applied_coupons ) ) { foreach ( $applied_coupons as $coupon_code ) { $coupon = new WC_Coupon( $coupon_code ); // 验证优惠券是否对当前购物车有效 if ( $coupon->is_valid() && $coupon->applies_to_cart() ) { $has_valid_coupon = true; break; } } } // 没有有效优惠券时阻止结账并提示 if ( ! $has_valid_coupon ) { wc_clear_notices(); wc_add_notice( '该商品需要使用有效优惠券才能完成结账,请联系店内工作人员获取', 'error' ); } } }
代码说明
- 先检测购物车中是否存在Redeem分类的商品,避免无目标商品时触发校验
- 遍历已应用的优惠券,通过
is_valid()和applies_to_cart()验证优惠券是否真正适配当前购物车(覆盖优惠券的使用限制、有效期等规则) - 仅当存在Redeem商品且无有效优惠券时,才显示错误提示并阻止结账
内容的提问来源于stack exchange,提问作者Candy
相关产品推荐
相关产品推荐

