You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WooCommerce结账强制使用优惠券:现有代码失效无法进入结账页求助

WooCommerce 强制Redeem分类商品结账需使用有效优惠券

原代码问题分析

你的代码存在两个核心问题:

  1. 硬编码固定优惠券0001,无法满足「任意有效优惠券」的需求
  2. 仅检查指定优惠券是否存在,未验证优惠券是否对当前购物车商品有效,同时错误提示逻辑可能干扰结账页加载

修正后的代码

将以下代码添加到你的主题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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 10:27:17