add_meta_box 是 WordPress 中用于在后台编辑页面添加自定义元框(Meta Box)的函数。它允许开发者在文章、页面、自定义文章类型等编辑页面中添加自定义字段或内容。以下是 add_meta_box 函数的参数及其说明:
函数原型
add_meta_box( $id, $title, $callback, $screen, $context, $priority, $callback_args );
参数说明
$id (string)
元框的唯一标识符(ID)。
必须是唯一的,通常使用前缀以避免冲突。
示例:'my_custom_meta_box'
$title (string)
元框的标题,显示在元框的顶部。
示例:'Custom Meta Box'
$callback (callable)
回调函数,用于输出元框的内容。
这个函数会接收两个参数:当前文章对象和元框的配置数组。
示例:'my_custom_meta_box_callback'
$screen (string|array|WP_Screen)
指定元框显示在哪个编辑页面。
可以是文章类型(如 'post'、'page')、自定义文章类型,或者是 'dashboard'、'link' 等。
如果希望在所有文章类型中显示,可以使用 array('post', 'page')。
示例:'post'
$context (string)
指定元框显示的位置。
可选值:'normal'(默认)、'side'、'advanced'。
'normal':在主要内容区域。
'side':在侧边栏。
'advanced':在高级选项区域。
示例:'normal'
$priority (string)
指定元框的显示优先级。
可选值:'high'、'core'、'default'、'low'。
'high':元框会显示在较高位置。
'default':默认优先级。
示例:'high'
$callback_args (array)
传递给回调函数的额外参数。
这个参数是可选的,通常用于传递自定义数据给回调函数。
示例:array('foo' => 'bar')
示例代码
function my_custom_meta_box_callback($post, $meta_box_args) {
// 输出元框内容
echo '<label for="my_custom_field">Custom Field:</label>';
echo '<input type="text" id="my_custom_field" name="my_custom_field" value="' . esc_attr(get_post_meta($post->ID, 'my_custom_field', true)) . '">';
}
function add_my_custom_meta_box() {
add_meta_box(
'my_custom_meta_box', // ID
'Custom Meta Box', // 标题
'my_custom_meta_box_callback', // 回调函数
'post', // 显示在文章编辑页面
'normal', // 上下文
'high' // 优先级
);
}
add_action('add_meta_boxes', 'add_my_custom_meta_box');