WooCommerce添加指定限量商品时自动移除购物车其他商品代码修复
问题排查与修复方案
原代码核心问题
- 逻辑覆盖不全:只处理了「当前加入的是限量鞋」的场景,完全没处理「当前加入的是普通商品、购物车已有限量鞋」的场景,你之前测试先加限量再加普通能生效属于偶发情况,实际逻辑不支持。
- 删除规则错误:仅记录最后一个非限量商品的key,只会删除1件普通商品,购物车内有多件普通商品时会残留。
- 判断逻辑模糊:没有明确约定限量款为必须保留的商品,多商品循环时容易出现变量覆盖,导致误删刚加入的限量款,就是你遇到的异常情况。
修复后代码
以下代码同时支持用产品ID或者EMI分类判断,你可以按需选择,默认同时兼容两种规则,后续新增EMI分类下的限量商品也不用修改代码:
add_action( 'woocommerce_add_to_cart', 'check_limited_product_cart_rule', 10, 6 ); function check_limited_product_cart_rule($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data) { // 配置参数:限量款产品ID、EMI分类ID $limited_product_ids = [348455, 348443]; $emi_category_id = 348; $notice_text = '购物车中存在EMI限量预售商品时,无法添加其他商品。'; // 判断当前加入的商品是不是限量款 $is_current_limited = in_array($product_id, $limited_product_ids) || has_term($emi_category_id, 'product_cat', $product_id); // 遍历购物车统计已有的限量款和普通款 $existing_limited = []; $existing_normal = []; foreach( WC()->cart->get_cart() as $key => $item ){ $item_is_limited = in_array($item['product_id'], $limited_product_ids) || has_term($emi_category_id, 'product_cat', $item['product_id']); if($item_is_limited){ $existing_limited[] = $key; }else{ $existing_normal[] = $key; } } // 场景1:当前加的是限量款,删掉所有已有的普通款 if($is_current_limited && !empty($existing_normal)){ foreach ($existing_normal as $normal_key) { WC()->cart->remove_cart_item($normal_key); } wc_add_notice( __($notice_text, 'theme_domain'), 'notice' ); return; } // 场景2:当前加的是普通款,购物车已有限量款,删掉刚加的普通款 if(!$is_current_limited && !empty($existing_limited)){ WC()->cart->remove_cart_item($cart_item_key); wc_add_notice( __($notice_text, 'theme_domain'), 'notice' ); return; } }
代码说明
- 自动识别EMI分类下的所有商品为限量预售款,后续新增同类商品不用修改ID配置
- 两种场景都做了完整处理,不会出现误删限量款的问题
- 购物车有多件普通商品时会全部清空,不会残留
- 提示语可直接修改
$notice_text变量调整即可
内容的提问来源于stack exchange,提问作者77advantage
相关产品推荐
相关产品推荐

