在启用HPOS的WooCommerce订单列表页显示订单项详情
在WooCommerce后台订单列表显示订单商品信息的有效方案
下面是适配新版WooCommerce的代码实现方法,无需插件即可恢复原生风格的订单信息展示:
1. 添加自定义列到订单列表
先在后台订单列表中新增一列,用于展示订单内的商品信息:
add_filter( 'manage_shop_order_posts_columns', 'add_order_items_column' ); function add_order_items_column( $columns ) { // 在订单号列后插入新列,可根据需求调整位置 $new_columns = array(); foreach ( $columns as $key => $value ) { $new_columns[ $key ] = $value; if ( 'order_number' === $key ) { $new_columns['order_items'] = '订单商品'; } } return $new_columns; }
2. 填充自定义列的商品信息
为新增列填充具体的订单商品内容,包含商品名称、数量,可变产品还会显示对应属性:
add_action( 'manage_shop_order_posts_custom_column', 'populate_order_items_column', 10, 2 ); function populate_order_items_column( $column, $post_id ) { if ( 'order_items' === $column ) { $order = wc_get_order( $post_id ); if ( ! $order ) return; $items_html = array(); foreach ( $order->get_items() as $item ) { $product = $item->get_product(); $item_name = $item->get_name(); // 处理可变产品的属性 if ( $item->get_variation_id() ) { $attributes = wc_get_formatted_variation( $item, true ); $item_name .= ' (' . $attributes . ')'; } // 添加商品数量 $item_name .= ' × ' . $item->get_quantity(); $items_html[] = $item_name; } echo implode( '<br>', $items_html ); } }
3. 可选:调整列宽度(优化显示)
如果新列显示过窄,可添加CSS调整宽度:
add_action( 'admin_head', 'adjust_order_items_column_width' ); function adjust_order_items_column_width() { echo '<style> .wp-list-table .column-order_items { width: 25%; min-width: 200px; } </style>'; }
使用说明
- 将以上代码添加到当前主题的
functions.php文件中,或通过自定义代码插件(如Code Snippets)插入 - 代码适配WooCommerce 3.0+版本,解决旧方法失效的问题
- 可根据需求修改列名称、宽度或显示内容
内容的提问来源于stack exchange,提问作者Edvinas Mc
相关产品推荐
相关产品推荐

