没有具体的答案,但评论时间太长。您还可以尝试查看WordPress core本身使用的代码。我知道你说过你不能使用自动添加页面的复选框,但你可以看看它是如何使用的。在WordPress代码中进行一点挖掘(使用一个像样的文本编辑器,您应该能够在整个WordPress代码库中搜索短语),就会发现:
/**
* Automatically add newly published page objects to menus with that as an option.
*
* @since 3.0.0
* @access private
*
* @param string $new_status The new status of the post object.
* @param string $old_status The old status of the post object.
* @param object $post The post object being transitioned from one status to another.
* @return void
*/
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 == $item->object_id )
continue 2;
}
wp_update_nav_menu_item( $menu_id, 0, $args );
}
}
此代码运行于:
add_action( \'transition_post_status\', \'_wp_auto_add_pages_to_menu\', 10, 3 );
也许这将为您指明正确的方向,也许您可以复制WP正在做的事情来做类似的事情。