WooCommerce购物车自定义分类restaurant添加数量限制问题求助
问题根源
你的代码逻辑错误核心有两点:
- 调用的
$cart_item['data']->get_category_ids()方法只能获取WooCommerce默认产品分类(slug为product_cat)的ID,无法读取你自定义的restaurant分类法的关联术语ID,导致统计的分类数据完全错误 - 你收集的
$ci是嵌套数组结构,直接用array_unique去重的逻辑无法正确统计购物车内不同restaurant分类项的数量
修复后代码
public function CheckRestaurantInCart($product_id){ // 购物车为空直接放行 if( WC()->cart->is_empty() ) return true; // 收集购物车所有产品关联的restaurant分类术语ID $cart_restaurant_ids = []; foreach ( WC()->cart->get_cart() as $cart_item ) { $item_restaurant_terms = get_the_terms( $cart_item['product_id'], 'restaurant' ); if ( $item_restaurant_terms && ! is_wp_error( $item_restaurant_terms ) ) { foreach ( $item_restaurant_terms as $term ) { $cart_restaurant_ids[] = $term->term_id; } } } // 去重得到购物车内已有不同restaurant的数量 $cart_restaurant_ids = array_unique( $cart_restaurant_ids ); $allowed_count = 2; // 获取当前要添加的产品所属的restaurant分类 $current_product_terms = get_the_terms( $product_id, 'restaurant' ); if ( !$current_product_terms || is_wp_error( $current_product_terms ) ) { // 当前产品没有关联restaurant分类直接放行,可根据需求调整逻辑 return true; } $current_restaurant_id = $current_product_terms[0]->term_id; // 购物车已有同分类直接放行 if ( in_array( $current_restaurant_id, $cart_restaurant_ids ) ) { return true; } // 超过数量限制拦截 if ( count( $cart_restaurant_ids ) >= $allowed_count ) { wc_add_notice( sprintf( __( '目前最多允许同时选购 %s 个不同餐厅的商品' ), $allowed_count ), 'error' ); return false; } return true; }
补充说明
- 上述代码默认每个产品只关联1个restaurant分类,如果你的业务支持单个产品关联多个restaurant分类,可自行调整判断逻辑
- 需要将函数挂载到WooCommerce的
woocommerce_add_to_cart_validation过滤器才能生效:
如果你是在类中使用:add_filter( 'woocommerce_add_to_cart_validation', [ $this, 'CheckRestaurantInCart' ], 10, 1 );
如果你是全局函数使用:add_filter( 'woocommerce_add_to_cart_validation', 'CheckRestaurantInCart', 10, 1 );
内容的提问来源于stack exchange,提问作者Tasha Banks
相关产品推荐
相关产品推荐

