我已经找到了解决问题的方法,通过反复阅读文档,查看源文件,并反复运行同一段代码来检查输出。
This is the solution I came up with, which works just perfectly for my needs:
// Get a list of all the menus that are part of the site
$menu_list = wp_get_nav_menus();
$menu_id = -1;
// Iterate over all the menus...
foreach( $menu_list as $menu ) {
// ...and find the one you want...
if( $menu->name === \'Main Menu\' ) {
// ...and get it\'s ID.
$menu_id = $menu->term_id;
}
}
// Delete everything except the Home entry
$menu_content = wp_get_nav_menu_items( \'Main Menu\' );
foreach( $menu_content as $menu_item ) {
if($menu_item->title !== \'Home\') {
wp_delete_post($menu_item->ID);
}
}
/* OTHER CODE USED FOR BUILDING PAGES, ETC CODE */
/**
* Menu building code
*
* @since 0.4.0pre1
*/
$menu_data = array(
\'menu-item-title\' => ( $menu_text !== \'\' ) ? wp_strip_all_tags( $menu_text ) : wp_strip_all_tags( $page_title ),
\'menu-item-object\' => \'page\',
\'menu-item-parent-id\' => ( $parent !== \'\' || $parent !== \'none\' ) ? intval( $parent ) : 0,
\'menu-item-position\' => ( $menu_position !== \'\' ) ? ( intval( $menu_position ) === 1 ? 2 : intval( $menu_position ) ): 2,
\'menu-item-object-id\' => $post_id,
\'menu-item-type\' => \'post_type\',
\'menu-item-status\' => \'publish\'
);
// Add this menu item to the existing nav menu if it is set to visible
if( intval( $menu_visible ) !== false ) {
wp_update_nav_menu_item( $menu_id, 0, $menu_data );
}
请随时提出对代码的任何改进或任何其他建议:)