add_meta_boxes
云策文档标注
概述
add_meta_boxes 是一个 WordPress 钩子,在所有内置元框添加后触发,用于注册自定义元框。它传递 $post_type 和 $post 两个参数,支持为任何文章类型添加元框。
关键要点
- 钩子名称:add_meta_boxes,在 WordPress 3.0.0 引入
- 参数:$post_type(字符串,文章类型)和 $post(WP_Post 对象)
- 最佳实践:推荐使用 add_meta_boxes_{post_type} 钩子,仅针对特定文章类型运行,减少不必要的钩子调用,且只接收 $post 一个参数
- 相关函数:register_and_do_post_meta_boxes() 用于注册默认元框
- 注意事项:在 PHP 7+ 中,如果编辑评论时触发此钩子,可能传递 WP_Comment 对象而非 WP_Post,需注意类型检查以避免错误
代码示例
// 通用用法,适用于所有文章类型
function adding_custom_meta_boxes( $post_type, $post ) {
add_meta_box(
'my-meta-box',
__( 'My Meta Box' ),
'render_my_meta_box',
'post',
'normal',
'default'
);
}
add_action( 'add_meta_boxes', 'adding_custom_meta_boxes', 10, 2 );// 针对特定文章类型的用法(最佳实践)
function adding_custom_meta_boxes( $post ) {
add_meta_box(
'my-meta-box',
__( 'My Meta Box' ),
'render_my_meta_box',
'post',
'normal',
'default'
);
}
add_action( 'add_meta_boxes_post', 'adding_custom_meta_boxes' );
原文内容
Fires after all built-in meta boxes have been added.
Parameters
$post_typestring-
Post type.
$postWP_Post-
Post object.
Source
do_action( 'add_meta_boxes', $post_type, $post );
Changelog
| Version | Description |
|---|---|
| 3.0.0 | Introduced. |
Skip to note 3 content
Konstantinos Raktivan
this note is to provide feedback for the documentation
the following code will produce an error in PHP >= 7
PHP Fatal Error: Uncaught Type Error: Argument #2 ($post) must be of type WP_Post, WP_Comment given
if I try to edit a comment navigating to
/wp-admin/comment.php?action=editcomment&c;=COMMENT_ID
it seems that the hook is fired with objects of type WP_Comment as well
add_action( 'add_meta_boxes', function( string $post_type, WP_Post $post ): void {} );Skip to note 4 content
Steven Lin
Example migrated from Codex:
Example usage:
function adding_custom_meta_boxes( $post_type, $post ) { add_meta_box( 'my-meta-box', __( 'My Meta Box' ), 'render_my_meta_box', 'post', 'normal', 'default' ); } add_action( 'add_meta_boxes', 'adding_custom_meta_boxes', 10, 2 );Example with a post-type specific call:
function adding_custom_meta_boxes( $post ) { add_meta_box( 'my-meta-box', __( 'My Meta Box' ), 'render_my_meta_box', 'post', 'normal', 'default' ); } add_action( 'add_meta_boxes_post', 'adding_custom_meta_boxes' );Both will accomplish the same thing. Best practice is to use
add_meta_boxes_{post-type}to create less unnecessary hooks for other post types.