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

Woocommerce特定分类最低下单限制与豁免分类设置报错排查

WooCommerce 下单规则代码修复方案

现有代码问题梳理

你当前的代码存在3个核心错误,直接导致触发异常提示:

  • 错误1:错误提示触发条件没有边界判断。当前只要Chilled商品数量小于3就弹出提示,没有排除购物车完全没有Chilled商品的场景,就是你遇到的无Chilled商品也弹提示的问题。
  • 错误2:Bundle分类判断的变量名错误。循环遍历购物车的变量是$product,但判断Bundle分类时用了未定义的$cart_item['product_id'],导致Bundle分类的判断完全失效,$cat_in_cart永远为false。
  • 错误3:Bundle判断逻辑加了错误的break终止符,只要循环第一个商品不是Bundle分类,就直接停止遍历后续商品,即便后面有Bundle商品也识别不到。

修复后完整代码

// Chilled分类最低购买数量规则
add_action( 'woocommerce_check_cart_items', 'chilled_set_min_total' );
function chilled_set_min_total() {
    // 仅在购物车、结账页生效
    if( is_cart() || is_checkout() ) {
        // 配置参数
        $minimum_chilled = 3;
        $total_chilled = 0;
        $has_bundle_in_cart = false;
        
        // 遍历购物车统计分类数据
        foreach ( WC()->cart->cart_contents as $cart_item ) {
            // 统计Chilled商品总数量
            if ( has_term( 'chilled', 'product_cat', $cart_item['product_id'] ) ) {
                $total_chilled += $cart_item['quantity'];
            }
            // 识别是否存在Bundle分类商品
            if ( has_term( 'bundles', 'product_cat', $cart_item['product_id'] ) ) {
                $has_bundle_in_cart = true;
            }
        }

        // 仅同时满足以下三个条件才弹出错误提示:
        // 1. 购物车有Chilled分类商品
        // 2. Chilled商品数量不足最低要求
        // 3. 购物车没有Bundle分类商品
        if ( $total_chilled > 0 && $total_chilled < $minimum_chilled && !$has_bundle_in_cart ) {
            wc_add_notice( sprintf( 
                '<strong>需至少购买%s件Chilled分类商品才可结账</strong><br />当前购物车Chilled商品数量:%s',
                $minimum_chilled,
                $total_chilled 
            ), 'error' );
        }
    }
}

修复说明

  • 完全匹配你设置的三条下单规则,无Chilled商品、有Bundle商品时都不会弹出错误提示
  • 替换了旧的全局$woocommerce调用,改用WooCommerce官方推荐的WC()方法调用,兼容性更好
  • 调整了变量命名,可读性更强,后续修改参数更方便

内容的提问来源于stack exchange,提问作者Giuls

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 12:39:02