如何在WooCommerce订单列表添加billing_city、billing_country字段
WooCommerce后台订单列表添加账单城市、国家字段实现方案
你可以通过WordPress管理列表钩子实现该需求,无需修改WooCommerce核心文件,代码可直接放入当前主题的functions.php文件或自定义功能插件中。
用到的核心钩子
manage_edit-shop_order_columns:传统存储模式下注册订单列表列头manage_shop_order_posts_custom_column:传统存储模式下输出列内容manage_woocommerce_page_wc-orders_columns:兼容HPOS高性能订单存储的列头注册钩子manage_woocommerce_page_wc-orders_custom_column:兼容HPOS高性能订单存储的列内容输出钩子
完整实现代码
1. 注册自定义列头
可以自定义列的插入位置,以下示例将新列放在「订单状态」列之后:
add_filter('manage_edit-shop_order_columns', 'custom_add_billing_address_columns'); // HPOS兼容钩子 add_filter('manage_woocommerce_page_wc-orders_columns', 'custom_add_billing_address_columns'); function custom_add_billing_address_columns($columns) { $new_columns = []; foreach ($columns as $key => $label) { $new_columns[$key] = $label; // 在订单状态列后插入新列,可修改$key值调整位置 if ($key === 'order_status') { $new_columns['billing_city'] = __('账单城市', 'woocommerce'); $new_columns['billing_country'] = __('账单国家/地区', 'woocommerce'); } } return $new_columns; }
2. 输出列对应内容
代码会自动获取订单的账单城市、国家信息,国家字段默认输出中文全称而非两位ISO编码:
add_action('manage_shop_order_posts_custom_column', 'custom_render_billing_address_columns', 10, 2); // HPOS兼容钩子 add_action('manage_woocommerce_page_wc-orders_custom_column', 'custom_render_billing_address_columns', 10, 2); function custom_render_billing_address_columns($column, $order_or_post_id) { $order = is_a($order_or_post_id, 'WC_Order') ? $order_or_post_id : wc_get_order($order_or_post_id); if (!$order) return; switch ($column) { case 'billing_city': echo esc_html($order->get_billing_city()); // 如需同时显示账单省/州,取消下一行注释即可 // echo ',' . esc_html($order->get_billing_state()); break; case 'billing_country': $country_code = $order->get_billing_country(); $countries = WC()->countries->get_countries(); echo esc_html($countries[$country_code] ?? $country_code); break; } }
可选扩展:让列支持点击排序
如果需要点击列头按照城市、国家排序,追加以下代码即可:
add_filter('manage_edit-shop_order_sortable_columns', 'custom_billing_columns_sortable'); add_filter('manage_woocommerce_page_wc-orders_sortable_columns', 'custom_billing_columns_sortable'); function custom_billing_columns_sortable($columns) { $columns['billing_city'] = 'billing_city'; $columns['billing_country'] = 'billing_country'; return $columns; }
注意事项
- 调整列位置时,只需修改列注册代码中
if ($key === 'order_status')里的order_status为目标列的ID即可,比如要放在「账单地址」列后就改为billing_address - 如果需要输出国家两位编码而非全称,直接替换国家输出部分的代码为
echo esc_html($order->get_billing_country());即可 - 代码同时兼容传统文章类型存储和WooCommerce高版本默认的HPOS高性能订单存储,无需额外适配
内容的提问来源于stack exchange,提问作者Lock2007
相关产品推荐
相关产品推荐

