wp_nav_menu_post_type_meta_boxes()
云策文档标注
概述
wp_nav_menu_post_type_meta_boxes() 函数用于为支持导航菜单的自定义文章类型创建元框,以便在菜单编辑器中添加菜单项。它通过遍历符合条件的文章类型,并应用过滤器来控制是否添加元框。
关键要点
- 函数获取所有设置了 'show_in_nav_menus' => true 的文章类型对象。
- 使用 apply_filters('nav_menu_meta_box_object', $post_type) 过滤器,允许开发者控制是否为特定文章类型添加元框。
- 为每个文章类型调用 add_meta_box() 添加元框,其中页面('page')类型具有更高的优先级('core')。
- 元框的回调函数为 wp_nav_menu_item_post_type_meta_box,用于在导航菜单编辑器中显示内容。
代码示例
function wp_nav_menu_post_type_meta_boxes() {
$post_types = get_post_types( array( 'show_in_nav_menus' => true ), 'object' );
if ( ! $post_types ) {
return;
}
foreach ( $post_types as $post_type ) {
$post_type = apply_filters( 'nav_menu_meta_box_object', $post_type );
if ( $post_type ) {
$id = $post_type->name;
$priority = ( 'page' === $post_type->name ? 'core' : 'default' );
add_meta_box(
"add-post-type-{$id}",
$post_type->labels->name,
'wp_nav_menu_item_post_type_meta_box',
'nav-menus',
'side',
$priority,
$post_type
);
}
}
}注意事项
- 此函数在 WordPress 3.0.0 版本中引入,主要用于后台导航菜单编辑器的初始化过程。
- 通过 'nav_menu_meta_box_object' 过滤器,开发者可以返回 false 来阻止为特定文章类型添加元框,实现自定义控制。
- 函数依赖于 get_post_types() 和 add_meta_box() 等核心函数,确保文章类型正确注册并显示在菜单编辑器中。
原文内容
Creates meta boxes for any post type menu item.
Description
.
Source
function wp_nav_menu_post_type_meta_boxes() {
$post_types = get_post_types( array( 'show_in_nav_menus' => true ), 'object' );
if ( ! $post_types ) {
return;
}
foreach ( $post_types as $post_type ) {
/**
* Filters whether a menu items meta box will be added for the current
* object type.
*
* If a falsey value is returned instead of an object, the menu items
* meta box for the current meta box object will not be added.
*
* @since 3.0.0
*
* @param WP_Post_Type|false $post_type The current object to add a menu items
* meta box for.
*/
$post_type = apply_filters( 'nav_menu_meta_box_object', $post_type );
if ( $post_type ) {
$id = $post_type->name;
// Give pages a higher priority.
$priority = ( 'page' === $post_type->name ? 'core' : 'default' );
add_meta_box(
"add-post-type-{$id}",
$post_type->labels->name,
'wp_nav_menu_item_post_type_meta_box',
'nav-menus',
'side',
$priority,
$post_type
);
}
}
}
Hooks
- apply_filters( ‘nav_menu_meta_box_object’, WP_Post_Type|false $post_type )
-
Filters whether a menu items meta box will be added for the current object type.
Changelog
| Version | Description |
|---|---|
| 3.0.0 | Introduced. |