WooCommerce ID1010可变商品多属性订单显示异常求助
解决WooCommerce可变商品多属性订单重复显示问题
问题场景
ID为1010的WooCommerce可变商品包含phys (best)和version (limit)两个属性值:
- 单独购买任一属性的商品时,显示内容正常匹配对应属性
- 同时购买两个属性的商品时,所有商品条目都重复显示第一个属性的内容
- 移除代码中循环内的
break语句后,虽能显示所有属性内容,但会把所有属性对应到每个商品条目上,不符合需求
问题根源
原detect_book_type函数仅接收商品ID,内部通过遍历整个订单的商品项来匹配ID,找到第一个匹配项后就break终止循环。这导致每个商品条目调用该函数时,都会处理订单中第一个匹配ID的商品属性,最终所有条目显示相同内容;若移除break,函数会遍历所有匹配项,将所有属性内容全部输出到当前条目下,造成属性乱匹配。
解决方案
修改函数逻辑,让函数直接接收当前订单商品项作为参数,针对性处理该商品的属性,无需遍历整个订单。同时修正用户元数据存储的键值错误。
修改后的代码
主函数detect_book_type
function detect_book_type( $item ){ $product = $item->get_product(); if ( !$product ) return; // 获取可变商品的父ID(若为变体商品) $product_id = $product->is_type('variation') ? $product->get_parent_id() : $product->get_id(); $current_user = wp_get_current_user(); switch( $product_id ): case '1': printf('<label>%s : </label> <input type="text" value="%s" readonly>', __('product number 1'), __('something (product 1)') ); break; case '2': printf('<label>%s : </label> <input type="text" value="%s" readonly>', __('product number 2'), __('something (product 2)') ); break; case '1010': printf('<label>%s : </label><h1>%s</h1>', __('Book address is'), __('THIS SECTION') ); // 直接处理当前商品项的属性 if ( $product->is_type('variation') ) { switch( $product->get_attribute('book terms') ): case 'phys (best)': printf('<label>%s:</label> <input type="text" value="%s" readonly>', __('sample text phys'), run_phys_books_func() ); break; case 'version (limit)': printf('<label>%s:</label> <input type="text" value="%s" readonly>', __('sample text limit'), run_limit_func() ); break; endswitch; } break; endswitch; }
修正后的run_limit_func函数
function run_limit_func() { if ($booooooks_item = get_user_meta(get_current_user_id(), 'version (limit)', true)) { $book_result = $booooooks_item; } else { // 自定义逻辑 $book_result = 'dummy_data'; // 修正meta键值,确保和读取时一致 update_user_meta(get_current_user_id(), 'version (limit)', $book_result); } return $book_result; }
调用方式
在订单商品循环模板中,传入当前订单商品项调用函数:
foreach ( $order->get_items() as $item ) { // 其他商品展示代码 detect_book_type( $item ); // 其他代码 }
效果说明
- 每个商品条目调用函数时,仅处理自身对应的属性内容,确保显示匹配
- 修正用户元数据的存储键值,避免数据读取异常
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

