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

WooCommerce限制stallholder用户仅可一次选购一个分组产品

解决WooCommerce限制stallholder角色仅能添加同一分组下商品的问题

原代码存在的核心问题

两次尝试均因逻辑漏洞导致功能失效:

  • 关键变量未定义:代码中使用$args但未赋值,wc_get_products($args)无法正确获取分组产品。
  • 分组关联逻辑错误:错误将分组子产品ID当作分类法传入has_term/get_the_terms,这两个函数的第二个参数应为分类法(如product_cat),而非产品ID。
  • 循环逻辑漏洞:遍历分组产品时每次重置$children数组,最终仅保留最后一个分组的子产品,无法覆盖所有分组关系。
  • 验证逻辑颠倒:第二次尝试中判断逻辑搞反,错误阻止同分组商品添加,反而允许不同分组商品共存。

正确实现代码

以下代码可实现需求:仅允许stallholder角色用户的购物车中存在来自同一个分组产品的商品,禁止同时添加不同分组下的子产品。

function limit_stallholder_to_single_grouped_product( $passed, $product_id, $quantity ) {
    // 仅针对stallholder角色生效
    if ( ! current_user_can('stallholder') ) {
        return $passed;
    }

    $current_product = wc_get_product( $product_id );
    $current_group_id = 0;

    // 获取当前产品所属的分组产品ID
    if ( $current_product->is_type('simple') && $parent_id = wp_get_post_parent_id( $product_id ) ) {
        $parent_product = wc_get_product( $parent_id );
        if ( $parent_product && $parent_product->is_type('grouped') ) {
            $current_group_id = $parent_id;
        }
    } elseif ( $current_product->is_type('grouped') ) {
        $current_group_id = $product_id;
    }

    // 若当前产品不属于任何分组,直接允许添加(可按需调整)
    if ( $current_group_id === 0 ) {
        return $passed;
    }

    // 遍历购物车,检查是否存在其他分组的产品
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        $cart_product = $cart_item['data'];
        $cart_group_id = 0;

        // 获取购物车商品所属的分组ID
        if ( $cart_product->is_type('simple') && $cart_parent_id = wp_get_post_parent_id( $cart_product->get_id() ) ) {
            $cart_parent_product = wc_get_product( $cart_parent_id );
            if ( $cart_parent_product && $cart_parent_product->is_type('grouped') ) {
                $cart_group_id = $cart_parent_id;
            }
        } elseif ( $cart_product->is_type('grouped') ) {
            $cart_group_id = $cart_product->get_id();
        }

        // 发现不同分组产品,阻止添加
        if ( $cart_group_id !== 0 && $cart_group_id !== $current_group_id ) {
            $passed = false;
            wc_add_notice( __('仅允许同时预订同一场次的摊位,请勿添加不同场次的商品。', 'woocommerce'), 'error' );
            break;
        }
    }

    return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'limit_stallholder_to_single_grouped_product', 10, 3 );

代码说明

  1. 角色过滤:仅对stallholder角色用户执行验证逻辑,其他角色不受限制。
  2. 分组识别:
    • 若添加的是分组子产品,通过父ID关联到所属分组产品。
    • 若添加的是分组产品本身,直接以其ID作为分组标识。
  3. 购物车校验:遍历购物车所有商品,逐一匹配分组ID,发现跨分组商品立即阻止添加并提示错误。
  4. 兼容处理:对不属于任何分组的普通产品默认允许添加,可根据业务需求调整此规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 19:37:06