启用HPOS的WooCommerce后台订单页添加自定义元框失败求助
WooCommerce订单后台添加元框的解决方案
针对你遇到的问题,以下是几种可行的解决方法:
方法一:确保代码在WooCommerce加载后执行
WooCommerce的shop_order自定义帖子类型是在插件加载完成后才注册的,直接使用add_meta_boxes可能因为时机过早导致无效。修改代码如下:
// 等待WooCommerce加载完成后注册元框 add_action( 'plugins_loaded', 'setup_custom_order_metabox' ); function setup_custom_order_metabox() { add_action( 'add_meta_boxes_shop_order', 'add_custom_order_meta_box' ); } function add_custom_order_meta_box() { add_meta_box( 'custom_meta_box', __( 'Facture' ), 'render_custom_order_metabox_content', 'shop_order', 'side', 'core' ); } function render_custom_order_metabox_content( $post ) { // 可选:获取对应订单对象,方便后续操作订单数据 $order = wc_get_order( $post->ID ); echo '<a href="#" class="button button-secondary">Test button</a>'; }
方法二:适配块编辑器(WooCommerce 5.0+)
如果你的WooCommerce版本启用了订单的块编辑器(Gutenberg),普通元框可能无法正常显示。可以先禁用订单的块编辑器,再添加元框:
// 禁用订单的块编辑器 add_filter( 'use_block_editor_for_post_type', 'disable_shop_order_block_editor', 10, 2 ); function disable_shop_order_block_editor( $use_block_editor, $post_type ) { return 'shop_order' === $post_type ? false : $use_block_editor; } // 注册订单元框 add_action( 'plugins_loaded', 'setup_custom_order_metabox' ); function setup_custom_order_metabox() { add_action( 'add_meta_boxes_shop_order', 'add_custom_order_meta_box' ); } function add_custom_order_meta_box() { add_meta_box( 'custom_meta_box', __( 'Facture' ), 'render_custom_order_metabox_content', 'shop_order', 'side', 'core' ); } function render_custom_order_metabox_content( $post ) { echo '<a href="#" class="button button-secondary">Test button</a>'; }
额外检查项
- 代码位置:将代码放在当前主题的
functions.php文件中,或者创建自定义插件存放代码(推荐,避免主题更新丢失)。 - 清除缓存:修改代码后清除WordPress缓存和浏览器缓存,确保新代码生效。
- 用户权限:确保当前登录用户拥有编辑订单的权限(如管理员角色)。
内容的提问来源于stack exchange,提问作者Pierre-Alexis Lebrun
相关产品推荐
相关产品推荐

