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

如何用PHP为WooCommerce按分类设置订单商品数量的最小/最大值

WooCommerce 分类订单规则自定义验证方案

需求说明

我有4个商品分类,需要实现以下订单校验规则:

  • 分类#1、#2、#3:订单中该三类商品总数必须为3件(最小/最大均为3),且不能与分类#4商品共存;
  • 分类#4:订单中仅能添加1件该分类商品,且不能与分类#1、#2、#3商品共存。

尝试过多个插件和代码片段均未满足需求,倾向通过自定义代码实现,以下是之前无效的代码:

// Validate minimum and maximum items per order based on categories
function custom_validate_cart_items($passed) {
    // Set your category IDs
    $category_ids = array(1, 2, 3);
    $category_id_single = 4;

    // Initialize counters and flags
    $category_count = 0;
    $category_single_count = 0;
    $has_category_ids = false;
    $has_category_single = false;

    // Loop through cart items
    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
        $product_id = $cart_item['product_id'];
        $product_cat_ids = wp_get_post_terms($product_id, 'product_cat', array('fields' => 'ids'));

        if (in_array($product_id, $category_ids)) {
            $category_count += $cart_item['quantity'];
            $has_category_ids = true;
        } elseif ($product_cat_ids && $product_cat_ids[0] == $category_id_single) {
            $category_single_count += $cart_item['quantity'];
            $has_category_single = true;
        }
    }

    // Check if the quantities exceed the limits
    if ($category_count < 3 && $has_category_single) {
        wc_add_notice(__('You must select a minimum of 3 items from categories 1, 2, or 3.'), 'error');
        $passed = false;
    }

    if ($category_single_count > 1 && ($category_count === 0 || $has_category_ids)) {
        wc_add_notice(__('You can only select 1 item from category 4.'), 'error');
        $passed = false;
    }

    // Check if items from Category 4 are being added when there are items from Categories 1, 2, or 3, and vice versa
    if ($has_category_ids && $has_category_single) {
        wc_add_notice(__('You cannot select items from category 4 if you have items from categories 1, 2, or 3, and vice versa.'), 'error');
        $passed = false;
    }

    return $passed;
}

add_filter('woocommerce_check_cart_items', 'custom_validate_cart_items', 10, 1);

原代码问题分析

  1. 分类判断逻辑错误:用in_array($product_id, $category_ids)将产品ID与分类ID对比,完全不符合分类校验逻辑;
  2. 分类4判断局限:仅取商品第一个分类ID判断,若商品属于多个分类会漏判;
  3. 数量校验不完整:仅在同时存在分类4商品时才校验分类1-3的数量,单独选分类1-3时未校验最小/最大3件的规则;
  4. 条件判断混乱:分类4数量校验的条件逻辑冗余且错误,导致规则触发异常。

修复后的代码

// WooCommerce 分类订单规则自定义验证
function custom_validate_cart_items($passed) {
    // 设置目标分类ID(请替换为实际分类ID)
    $cat_group_1_ids = array(1, 2, 3); // 分类1、2、3分组
    $cat_single_id = 4; // 分类4单独分组

    // 初始化计数器与状态标记
    $group1_total_qty = 0;
    $single_total_qty = 0;
    $has_group1_items = false;
    $has_single_items = false;

    // 遍历购物车中所有商品
    foreach (WC()->cart->get_cart() as $cart_item) {
        $product = $cart_item['data'];
        // 获取商品所属的所有分类ID
        $product_cat_ids = wp_get_post_terms($product->get_id(), 'product_cat', array('fields' => 'ids'));

        // 判断商品是否属于分类1-3分组
        if (!empty(array_intersect($product_cat_ids, $cat_group_1_ids))) {
            $group1_total_qty += $cart_item['quantity'];
            $has_group1_items = true;
        }

        // 判断商品是否属于分类4
        if (in_array($cat_single_id, $product_cat_ids)) {
            $single_total_qty += $cart_item['quantity'];
            $has_single_items = true;
        }
    }

    // 校验规则1:两个分组商品不能同时存在
    if ($has_group1_items && $has_single_items) {
        wc_add_notice(__('分类4商品与分类1、2、3商品不能同时加入购物车。'), 'error');
        $passed = false;
    }

    // 校验规则2:分类1-3分组商品总数必须为3件
    if ($has_group1_items && ($group1_total_qty < 3 || $group1_total_qty > 3)) {
        wc_add_notice(__('分类1、2、3商品总数必须为3件。'), 'error');
        $passed = false;
    }

    // 校验规则3:分类4商品只能添加1件
    if ($has_single_items && $single_total_qty > 1) {
        wc_add_notice(__('分类4商品仅能添加1件。'), 'error');
        $passed = false;
    }

    return $passed;
}
add_filter('woocommerce_check_cart_items', 'custom_validate_cart_items', 10, 1);

修复说明

  • 修正分类判断逻辑:使用array_intersect判断商品是否属于分类1-3分组,确保多分类商品不会漏判;
  • 完善规则校验顺序:先校验跨分组冲突,再分别校验各组数量规则,逻辑更清晰;
  • 补充分类1-3的最大数量校验,完全匹配需求中“最小/最大为3件”的要求;
  • 简化计数器与标记逻辑,避免冗余判断,提升代码可读性与稳定性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 14:23:14