add_meta_boxes_{$post_type}
云策文档标注
概述
add_meta_boxes_{$post_type} 是一个动态 Hook,在 WordPress 为特定文章类型添加所有内置元框后触发,允许开发者针对该文章类型添加自定义元框。
关键要点
- Hook 名称是动态的,{$post_type} 部分替换为具体文章类型,例如 add_meta_boxes_post、add_meta_boxes_page。
- 触发时机在所有内置元框添加之后,用于上下文相关的文章类型。
- 参数为 $post(WP_Post 对象),代表当前文章对象。
- 源调用为 do_action("add_meta_boxes_{$post_type}", $post);。
- 自 WordPress 3.0.0 版本引入。
代码示例
/**
* Register meta box(es).
*/
function wpdocs_register_meta_boxes() {
add_meta_box( 'meta-box-id', __( 'My Meta Box', 'textdomain' ), 'wpdocs_my_display_callback', 'post' );
}
add_action( 'add_meta_boxes', 'wpdocs_register_meta_boxes' );
/**
* Meta box display callback.
*
* @param WP_Post $post Current post object.
*/
function wpdocs_my_display_callback( $post ) {
// Display code/markup goes here. Don't forget to include nonces!
}
/**
* Save meta box content.
*
* @param int $post_id Post ID
*/
function wpdocs_save_meta_box( $post_id ) {
// Save logic goes here. Don't forget to include nonce checks!
}
add_action( 'save_post', 'wpdocs_save_meta_box' );注意事项
- 注意区分 add_meta_boxes(通用 Hook)和 add_meta_boxes_{$post_type}(特定文章类型 Hook),避免混淆使用。
- 在添加自定义元框时,确保包含 nonce 以增强安全性。
原文内容
Fires after all built-in meta boxes have been added, contextually for the given post type.
Description
The dynamic portion of the hook name, $post_type, refers to the post type of the post.
Possible hook names include:
add_meta_boxes_postadd_meta_boxes_pageadd_meta_boxes_attachment
Parameters
$postWP_Post-
Post object.
Source
do_action( "add_meta_boxes_{$post_type}", $post );
Changelog
| Version | Description |
|---|---|
| 3.0.0 | Introduced. |
Skip to note 2 content
Aurovrata Venet
/** * Register meta box(es). */ function wpdocs_register_meta_boxes() { add_meta_box( 'meta-box-id', __( 'My Meta Box', 'textdomain' ), 'wpdocs_my_display_callback', 'post' ); } add_action( 'add_meta_boxes', 'wpdocs_register_meta_boxes' ); /** * Meta box display callback. * * @param WP_Post $post Current post object. */ function wpdocs_my_display_callback( $post ) { // Display code/markup goes here. Don't forget to include nonces! } /** * Save meta box content. * * @param int $post_id Post ID */ function wpdocs_save_meta_box( $post_id ) { // Save logic goes here. Don't forget to include nonce checks! } add_action( 'save_post', 'wpdocs_save_meta_box' );