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

WooCommerce限制购物车仅含指定分类下的一件商品

解决WooCommerce分类a/b总共仅能购买1件的限制需求

没问题,我帮你调整这段代码,让它实现「分类a和b总共只能买1件」的限制,而不是原来的各买1件。下面是修改后的完整代码:

add_filter( 'woocommerce_add_to_cart_validation', 'allowed_total_quantity_for_restricted_categories', 10, 2 );
function allowed_total_quantity_for_restricted_categories( $passed, $product_id ) { 
    $max_total_products = 1; // 限制的总数量
    $running_total_qty = 0; 
    // 要限制的分类slug,注意这里是数组每个元素单独放一个slug
    $restricted_product_cats = array('cat-a', 'cat-b'); 

    // 检查当前产品是否属于限制分类之一
    $current_product_in_restricted = has_term( $restricted_product_cats, 'product_cat', $product_id );

    // 如果当前产品不在限制分类里,直接放行
    if ( !$current_product_in_restricted ) {
        return $passed;
    }

    // 统计购物车里所有属于限制分类的商品总数量
    foreach ( WC()->cart->get_cart() as $cart_item ) { 
        if( has_term( $restricted_product_cats, 'product_cat', $cart_item['product_id'] )) { 
            $running_total_qty += (int) $cart_item['quantity']; 
        }
    }

    // 如果总数量已经达到上限,阻止加入购物车并提示错误
    if ( $running_total_qty >= $max_total_products ) {
        $passed = false;
        wc_add_notice( '你只能购买分类A或分类B中的一件商品', 'error' );
    }

    return $passed;
}

关键修改说明:

  • 修正分类数组写法:原代码把两个分类slug放在同一个字符串里,导致has_term无法正确识别,现在改成数组每个元素对应一个slug。
  • 调整统计逻辑:不再针对当前产品的分类单独统计,而是统计所有限制分类下的商品总数量,这样不管用户选的是a还是b,加起来最多1件。
  • 增加分类判断:先检查当前产品是否在限制分类里,如果不在直接放行,避免影响其他分类的商品。
  • 补充错误提示:当用户超过限制时,给出明确的错误提示,提升用户体验。
  • 确保返回验证结果:原代码没有返回$passed值,这会导致WooCommerce的购物车验证失效,现在补充了返回逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:59:19