代码的问题在于,它实际上并没有将链接添加到菜单,而只是添加到菜单的输出,因此使用了过滤器(add\\u 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
我认为它是这样做的:
第一项-“菜单项位置”1第一项第一子项-“菜单项位置”1第一项第二子项-“菜单项位置”2第三项-“菜单项位置”3第四项-“菜单项位置”4