WordPress添加元数据设置项函数:add_meta_box

WordPress函数add_meta_box用于为指定文章类型添加元数据设置项,例如可以为文章添加一个关键词设置单元。

add_meta_box( string $id, string $title, callable $callback, string|array|WP_Screen $screen = null, string $context = 'advanced', string $priority = 'default', array $callback_args = null )

函数参数

$id

字符串

用于盒子ID属性。

$title

字符串

盒子的标题

$callback

回调函数的名称

$screen

字符串或数组

提供文章类型的名称,例如:post、page、link、comment

$context

字符串,默认值:advanced

盒子显示位置,可用值:normal、side、advanced

$priority

字符串,默认值:default

显示位置,可用值:high、core、low、default

$callback_args

数组

传递给回调函数的第二个参数

函数使用示例

以下示例在文章的侧边栏添加一个关键词设置项,这里没有编写保存数据功能:

function bzg_meta_box_callback($meta_id) {
	$outline = '<label for="post-keywords">关键词:</label>';
	$post_keywords = get_post_meta($meta_id->ID, 'post_keywords', true);
	$outline .= '<input type="text" name="post_keywords" id="post-keywords" size="16" value="' . esc_attr($post_keywords) . '">';
	echo $outline;
}
function bzg_register_meta_box() {
    add_meta_box('post-keywords', '关键词设置', 'bzg_meta_box_callback', 'post', 'side', 'high');
}
add_action('add_meta_boxes', 'bzg_register_meta_box');

在经典编辑器下显示效果如下:

WordPress为文章添加元数据设置项

扩展阅读

add_meta_box()函数位于:wp-admin/includes/template.php

相关函数:

  • register_and_do_post_meta_boxes()
  • wp_add_dashboard_widget()
  • do_meta_boxes()
  • wp_nav_menu_setup()
阿里云