_wp_auto_add_pages_to_menu()
云策文档标注
概述
_wp_auto_add_pages_to_menu() 是一个 WordPress 内部函数,用于在页面发布时自动将其添加到启用了自动添加选项的导航菜单中。它通过检查页面状态和菜单设置,确保新发布的顶级页面被正确添加到指定菜单。
关键要点
- 函数在页面状态从非发布状态变为发布状态时触发,仅处理页面类型(post_type 为 'page')且无父页面的情况。
- 通过 get_option('nav_menu_options') 获取菜单自动添加设置,仅当设置存在且包含 'auto_add' 数组时才执行操作。
- 使用 wp_update_nav_menu_item() 将页面作为菜单项添加到每个指定菜单中,避免重复添加已存在的页面。
- 函数依赖于 WordPress 核心的导航菜单相关函数,如 wp_get_nav_menu_items() 和 wp_update_nav_menu_item()。
代码示例
function _wp_auto_add_pages_to_menu( $new_status, $old_status, $post ) {
if ( 'publish' !== $new_status || 'publish' === $old_status || 'page' !== $post->post_type ) {
return;
}
if ( ! empty( $post->post_parent ) ) {
return;
}
$auto_add = get_option( 'nav_menu_options' );
if ( empty( $auto_add ) || ! is_array( $auto_add ) || ! isset( $auto_add['auto_add'] ) ) {
return;
}
$auto_add = $auto_add['auto_add'];
if ( empty( $auto_add ) || ! is_array( $auto_add ) ) {
return;
}
$args = array(
'menu-item-object-id' => $post->ID,
'menu-item-object' => $post->post_type,
'menu-item-type' => 'post_type',
'menu-item-status' => 'publish',
);
foreach ( $auto_add as $menu_id ) {
$items = wp_get_nav_menu_items( $menu_id, array( 'post_status' => 'publish,draft' ) );
if ( ! is_array( $items ) ) {
continue;
}
foreach ( $items as $item ) {
if ( $post->ID === (int) $item->object_id ) {
continue 2;
}
}
wp_update_nav_menu_item( $menu_id, 0, $args );
}
}注意事项
- 此函数是 WordPress 核心内部函数,通常不应直接调用,而是通过页面发布状态转换自动触发。
- 仅适用于顶级页面(无父页面),子页面不会被自动添加到菜单中。
- 需要正确配置导航菜单的自动添加选项(nav_menu_options 中的 'auto_add' 数组),否则函数会提前返回。
- 函数在 WordPress 3.0.0 版本中引入,开发者应确保兼容性。
原文内容
Automatically add newly published page objects to menus with that as an option.
Parameters
$new_statusstringrequired-
The new status of the post object.
$old_statusstringrequired-
The old status of the post object.
$postWP_Postrequired-
The post object being transitioned from one status to another.
Source
function _wp_auto_add_pages_to_menu( $new_status, $old_status, $post ) {
if ( 'publish' !== $new_status || 'publish' === $old_status || 'page' !== $post->post_type ) {
return;
}
if ( ! empty( $post->post_parent ) ) {
return;
}
$auto_add = get_option( 'nav_menu_options' );
if ( empty( $auto_add ) || ! is_array( $auto_add ) || ! isset( $auto_add['auto_add'] ) ) {
return;
}
$auto_add = $auto_add['auto_add'];
if ( empty( $auto_add ) || ! is_array( $auto_add ) ) {
return;
}
$args = array(
'menu-item-object-id' => $post->ID,
'menu-item-object' => $post->post_type,
'menu-item-type' => 'post_type',
'menu-item-status' => 'publish',
);
foreach ( $auto_add as $menu_id ) {
$items = wp_get_nav_menu_items( $menu_id, array( 'post_status' => 'publish,draft' ) );
if ( ! is_array( $items ) ) {
continue;
}
foreach ( $items as $item ) {
if ( $post->ID === (int) $item->object_id ) {
continue 2;
}
}
wp_update_nav_menu_item( $menu_id, 0, $args );
}
}
Changelog
| Version | Description |
|---|---|
| 3.0.0 | Introduced. |