环境:wordpress6、twentytwentyone模板
一、wp-content/themes/twentytwentyone/functions.php 添加以下代码:
1、注册 (左边是别名,右边是名称。别名会用在导航栏的调用上,名称则显示在菜单后台页面上:外观->菜单)
register_nav_menus(array('primary' => esc_html__( 'Primary menu', 'twentytwentyone' ),'footer' => esc_html__( 'Secondary menu', 'twentytwentyone' ),));2、重写类
class Custom_Walker_Nav_Menu extends Walker_Nav_Menu {//在子菜单项之前输出子菜单的起始标记function start_lvl(&$output, $depth = 0, $args = array()) {$indent = str_repeat("\t", $depth);$output .= "\n$indent<ul class=\"sub-menu\">\n";}//在子菜单项之后输出子菜单的结束标记function end_lvl(&$output, $depth = 0, $args = array()) {$indent = str_repeat("\t", $depth);$output .= "$indent</ul>\n";}//输出每个菜单项的起始标记和内容function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {$indent = ($depth) ? str_repeat("\t", $depth) : '';$output .= $indent . '<li';// 添加 "nav-current" 类到当前活动菜单项if (in_array('current-menu-item', $item->classes) || in_array('current-menu-parent', $item->classes)) {$output .= ' class="nav-current"';}$output .= '><a href="' . $item->url . '">' . $item->title . '</a>';}//输出每个菜单项的结束标记function end_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {if ($args->walker->has_children) {$output .= '</ul>';}$output .= "</li>\n";}
}
二、导航栏调用
<nav class="nav-bar"><div class="nav-wrap"><?phpecho wp_nav_menu(array('theme_location' => 'primary','menu_class' => 'nav','container' => 'ul','walker' => new Custom_Walker_Nav_Menu(),));?></div></nav>