WooCommerce禁止混合添加simple/other商品并提示,代码报503错误求助
购物车商品类型限制功能报错排查与修复
我需要在WooCommerce中实现购物车商品类型限制:现有simple和other两种商品类型,要求购物车中若已有simple类型商品,仅能继续添加simple类型;若已有other类型商品,仅能继续添加other类型,禁止同时添加两种类型商品。我用了以下代码实现,但运行时出现503错误,无法正常生效:
add_action('woocommerce_add_to_cart', 'custome_add_to_cart', 10, 6); function custome_add_to_cart($cart_id, $product_id, $request_quantity, $variation_id, $variation, $cart_item_data) { global $woocommerce; //print_r($cart_item_data); //Current // die(); //check if product already in cart if ( sizeof( WC()->cart->get_cart() ) > 0 ) { foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { $product_type = $cart_item['type']; if ($product_type == 'other'){ if($cart_item_data['type'] == 'other'){ WC()->cart->add_to_cart( $product_id ); // print_r($cart_item); //Old Cart // die(); }else{ wc_print_notice( 'This type of product not added 1', 'notice' ); } }else{ //print_r($cart_item); //Old Cart if($cart_item_data['type'] != 'other'){ WC()->cart->add_to_cart( $product_id ); }else{ wc_print_notice( 'This type of product not added 2', 'notice' ); exit; } } } } }
错误原因分析
- 无限递归调用:在
woocommerce_add_to_cart钩子内再次调用WC()->cart->add_to_cart(),会反复触发钩子本身,导致服务器资源耗尽,出现503错误。 - 商品类型获取不可靠:依赖
cart_item_data['type']获取当前商品类型,这个字段并非始终存在,容易导致判断失效。 - 逻辑冗余+流程中断:遍历所有购物车商品属于多余操作,且使用
exit会直接中断页面正常流程,引发异常。
修复后的代码
add_action('woocommerce_add_to_cart_validation', 'restrict_cart_product_types', 10, 6); function restrict_cart_product_types($passed, $product_id, $quantity, $variation_id = '', $variations = '', $cart_item_data = '') { // 获取当前要添加的商品对象(优先取变体ID) $current_product = wc_get_product($variation_id ? $variation_id : $product_id); $current_type = $current_product->get_type(); // 购物车为空时直接允许添加 if (WC()->cart->is_empty()) { return $passed; } // 获取购物车中已存在的商品类型(取第一个即可,因为已有类型限制) $cart_type = ''; foreach (WC()->cart->get_cart() as $cart_item) { $cart_type = $cart_item['data']->get_type(); break; } // 类型不匹配时阻止添加并提示 if ($current_type !== $cart_type) { $type_name = $cart_type === 'simple' ? '普通商品' : '特殊商品'; wc_add_notice("购物车中已有{$type_name},无法添加其他类型的商品", 'error'); $passed = false; } return $passed; }
修复说明
- 改用正确钩子:使用
woocommerce_add_to_cart_validation钩子,这是WooCommerce官方提供的购物车添加验证钩子,返回false即可直接阻止商品添加,不会触发递归。 - 可靠获取商品类型:通过
wc_get_product()获取商品对象,再调用get_type()获取类型,确保类型判断准确。 - 简化逻辑:仅需取购物车中第一个商品的类型做对比,避免不必要的遍历。
- 规范错误提示:使用
wc_add_notice输出错误信息,通过返回值控制添加操作,不中断页面正常流程。
内容的提问来源于stack exchange,提问作者user12485091
相关产品推荐
相关产品推荐

