WooCommerce结账页存在landing-page分类商品时移除其他商品求助
WooCommerce 购物车存在指定分类时移除其他商品代码修改方案
你原来的代码直接调用empty_cart()会清空所有商品,我们可以调整逻辑为:先遍历购物车标记出目标分类商品,同时收集所有非目标分类的商品ID,确认存在目标分类商品后,仅删除非目标分类的商品即可。
修改后完整代码如下:
add_action('woocommerce_checkout_before_customer_details', 'check_if_landing_page_category_is_on_cart'); function check_if_landing_page_category_is_on_cart() { $target_categories = array('landing-page'); $has_target_category = false; $items_to_remove = array(); // 第一步遍历购物车,标记目标分类、收集待删除商品 foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { if ( has_term( $target_categories, 'product_cat', $cart_item['product_id'] ) ) { $has_target_category = true; } else { // 非目标分类商品加入待删除列表 $items_to_remove[] = $cart_item_key; } } // 第二步:如果存在目标分类,删除其他商品 if ( $has_target_category ) { foreach ( $items_to_remove as $item_key ) { WC()->cart->remove_cart_item( $item_key ); } // 保留原有隐藏优惠券表单的逻辑 ?> <style> .coupon-form { display: none; } </style> <?php } }
修改说明:
- 代码不再调用全局
$woocommerce,直接用WC()单例调用购物车方法,更符合WooCommerce开发规范 - 优先遍历完所有商品再执行删除操作,避免遍历过程中修改购物车结构导致的遍历异常
- 后续如果需要新增多个目标分类,直接往
$target_categories数组中添加分类别名即可,无需修改其他逻辑
内容的提问来源于stack exchange,提问作者user6684898
相关产品推荐
相关产品推荐

