WooCommerce跨类别加购限制逻辑错误:同类别商品无法共存求助
修复方案:限制Pickup与Ship类商品不能同时加入购物车
问题根源
原代码使用布尔值$both_categories_in_cart仅标记购物车中是否存在限制类商品,未区分具体类别。当加入第二个同类别的限制商品时,错误判定为“同时存在两类商品”,触发了不必要的清空逻辑。
修复后的代码
add_action( 'woocommerce_check_cart_items','prevent_multiple_category'); function prevent_multiple_category() { $disallowed_categories = array( 'pickup', 'ship' ); $current_cart_category = null; // 存储购物车中已有的限制类别 $cart_items = WC()->cart->get_cart(); foreach ( $cart_items as $cart_item ) { $product_id = $cart_item['product_id']; $product_categories = get_the_terms( $product_id, 'product_cat' ); // 容错处理:商品无分类或分类获取失败时跳过 if ( ! $product_categories || is_wp_error( $product_categories ) ) { continue; } $product_categories_slugs = array_map( function( $term ) { return $term->slug; }, $product_categories ); // 获取当前商品所属的限制类别(取第一个匹配项) $intersect = array_intersect( $product_categories_slugs, $disallowed_categories ); if ( ! empty( $intersect ) ) { $item_category = reset( $intersect ); if ( $current_cart_category === null ) { // 购物车无限制类商品,记录当前类别 $current_cart_category = $item_category; } else if ( $current_cart_category !== $item_category ) { // 购物车已有另一类限制商品,触发错误 wc_add_notice( __( 'You can not add Pickup Products and Shipping Products in the cart together.', 'text-domain' ), 'error' ); WC()->cart->empty_cart(); add_filter('woocommerce_cart_item_removed_notice_type', '__return_null'); break; } // 类别相同时,不做任何操作,继续遍历 } } }
关键修改说明
- 新增
$current_cart_category变量,精准记录购物车中已存在的限制类别(pickup或ship) - 通过
reset( $intersect )获取当前商品的具体限制类别(默认每个商品仅属于两类中的一类) - 仅当购物车中已存在的限制类别与当前商品类别不同时,才触发错误提示和清空逻辑
- 增加了商品无分类、分类获取失败的容错处理,避免代码报错
内容的提问来源于stack exchange,提问作者Abbasi
相关产品推荐
相关产品推荐

