代码的问题在于,它实际上并未将链接添加到菜单,而仅添加了菜单的输出,因此使用了过滤器(add_filter),因此即使您实际上不过滤菜单的输出,有一个菜单,您的链接将与您使用的代码一起显示。但是要创建链接并将其添加到菜单,您可以使用以下代码:
$run_once = get_option('menu_check');
if (!$run_once){
//give your menu a name
$name = 'theme default menu';
//create the menu
$menu_id = wp_create_nav_menu($name);
//then get the menu object by its name
$menu = get_term_by( 'name', $name, 'nav_menu' );
//then add the actuall link/ menu item and you do this for each item you want to add
wp_update_nav_menu_item($menu->term_id, 0, array(
'menu-item-title' => __('Home'),
'menu-item-classes' => 'home',
'menu-item-url' => home_url( '/' ),
'menu-item-status' => 'publish'));
//then you set the wanted theme location
$locations = get_theme_mod('nav_menu_locations');
$locations['main-menu'] = $menu->term_id;
set_theme_mod( 'nav_menu_locations', $locations );
// then update the menu_check option to make sure this code only runs once
update_option('menu_check', true);
}
我评论了所有内容以使其更简单。
要创建子页面/子页面/第二级菜单(您可以如何调用它),只需menu-item-parent-id
在新项目中设置,例如:
//create the top level menu item (home)
$top_menu = wp_update_nav_menu_item($menu->term_id, 0, array(
'menu-item-title' => __('Home'),
'menu-item-classes' => 'home',
'menu-item-url' => home_url( '/' ),
'menu-item-status' => 'publish'
'menu-item-parent-id' => 0,
));
//Sub menu item (first child)
$first_child = wp_update_nav_menu_item($menu->term_id, 0, array(
'menu-item-title' => __('First_Child'),
'menu-item-classes' => 'home',
'menu-item-url' => home_url( '/' ),
'menu-item-status' => 'publish'
'menu-item-parent-id' => $top_menu,
));
//Sub Sub menu item (first child)
$Second_child = wp_update_nav_menu_item($menu->term_id, 0, array(
'menu-item-title' => __('Second_Child'),
'menu-item-classes' => 'home',
'menu-item-url' => home_url( '/' ),
'menu-item-status' => 'publish'
'menu-item-parent-id' => $first_child,
));
您也可以通过代码设置位置menu-item-position
,我认为这样做是这样的:
- 第一项-'menu-item-position'=> 1
- 第一个孩子的第一个孩子-'menu-item-position'=> 1
- 第一项第二个孩子-'menu-item-position'=> 1
- 第一项第二个孩子第一个孩子-'menu-item-position'=> 1
- 第二项-'menu-item-position'=> 2
- 第三项-'菜单项位置'=> 3
- 第四项-'菜单项位置'=> 4