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

WooCommerce实现单订单仅允许选购同一产品分类的商品

WooCommerce 限制同一订单仅可选购同一分类下的多款商品

直接用下面这段代码就能实现需求:允许同一分类下的多款商品加入购物车,但禁止跨分类添加,添加时会弹出提示。

add_filter( 'woocommerce_add_to_cart_validation', 'restrict_cart_to_single_product_category', 10, 3 );
function restrict_cart_to_single_product_category( $passed, $product_id, $quantity ) {
    // 购物车为空的话直接放行
    if ( empty( WC()->cart->get_cart() ) ) {
        return $passed;
    }

    // 获取要添加商品的所有分类slug
    $new_product_cats = get_the_terms( $product_id, 'product_cat' );
    if ( ! $new_product_cats || is_wp_error( $new_product_cats ) ) {
        return $passed;
    }
    $new_cat_slugs = wp_list_pluck( $new_product_cats, 'slug' );

    // 收集购物车已有商品的所有分类slug并去重
    $existing_cat_slugs = array();
    foreach ( WC()->cart->get_cart() as $item ) {
        $item_cats = get_the_terms( $item['product_id'], 'product_cat' );
        if ( $item_cats && ! is_wp_error( $item_cats ) ) {
            foreach ( $item_cats as $cat ) {
                $existing_cat_slugs[] = $cat->slug;
            }
        }
    }
    $existing_cat_slugs = array_unique( $existing_cat_slugs );

    // 检查要加的商品和购物车已有商品有没有共同分类
    $common_cats = array_intersect( $new_cat_slugs, $existing_cat_slugs );
    if ( empty( $common_cats ) ) {
        wc_add_notice( '抱歉,同一订单只能选同一分类下的商品,请先清空购物车里其他分类的商品再添加。', 'error' );
        $passed = false;
    }

    return $passed;
}

使用说明

  • 把这段代码粘贴到你当前主题的functions.php文件末尾,或者用专门的自定义代码插件(比如Code Snippets)来添加,避免主题更新后代码丢失。
  • 逻辑说明:购物车为空时随便加;购物车有商品时,检查新商品的分类和已有商品的分类是否有重叠,没有重叠就阻止添加并弹出提示。比如购物车里已经有accessories分类的袜子和帽子,再加同分类的商品没问题,但加clothing分类的上衣就会被拦下来。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 19:25:22