2026年11月12日
2026年11月12日
自定义 WordPress 导航菜单:Walker_Nav_Menu、下拉菜单与汉堡菜单
本文是日语原文的本地化版本。 阅读日语原文
前言
“想自由控制页头导航的 HTML”“想实现下拉菜单或汉堡菜单”“想给菜单项添加图标或徽标”——自定义 Walker_Nav_Menu 类,就能完全控制 WordPress 导航的输出。
症状与原因
wp_nav_menu() 的默认输出很难控制 CSS 类或插入自定义 HTML,有时无法构造出现代设计所需的结构。通过扩展 Walker_Nav_Menu,就可以完全自定义输出的 HTML。
解决步骤
步骤1:注册导航菜单
// functions.php:注册导航菜单区域
add_action( 'after_setup_theme', function() {
register_nav_menus( [
'primary' => '全局导航',
'footer' => '页脚导航',
'mobile' => '移动端菜单',
'social' => '社交链接',
] );
} );
步骤2:用 wp_nav_menu() 输出基本导航
// header.php:全局导航
wp_nav_menu( [
'theme_location' => 'primary', // 已注册的菜单区域的 ID
'container' => 'nav', // 外层包装元素(设为 false 则禁用)
'container_class' => 'global-nav',
'container_id' => 'global-nav',
'menu_class' => 'nav-list',
'menu_id' => 'nav-list',
'echo' => true,
'fallback_cb' => false, // 未设置菜单时不显示任何内容
'depth' => 3, // 显示的菜单层级深度
'items_wrap' => '<ul id="%1$s" class="%2$s" role="list">%3$s</ul>',
] );
步骤3:用 Walker_Nav_Menu 实现自定义输出
// functions.php:自定义 NavWalker
class My_Nav_Walker extends Walker_Nav_Menu {
// 菜单项的起始标签
public function start_el( &$output, $item, $depth = 0, $args = null, $id = 0 ) {
$classes = empty( $item->classes ) ? [] : (array) $item->classes;
$classes[] = 'nav-item';
$classes[] = 'menu-item-' . $item->ID;
// 当前页面对应的菜单项
if ( in_array( 'current-menu-item', $classes, true ) ) {
$classes[] = 'is-active';
}
// 有子菜单时
$has_children = in_array( 'menu-item-has-children', $classes, true );
if ( $has_children ) {
$classes[] = 'has-dropdown';
}
$class_str = implode( ' ', array_filter( array_unique( $classes ) ) );
$output .= '<li class="' . esc_attr( $class_str ) . '">';
// a 标签的属性
$atts = [];
$atts['href'] = ! empty( $item->url ) ? $item->url : '#';
$atts['title'] = ! empty( $item->attr_title ) ? $item->attr_title : '';
$atts['target'] = ! empty( $item->target ) ? $item->target : '';
$atts['rel'] = ! empty( $item->xfn ) ? $item->xfn : '';
// 当前页面设置 aria-current
if ( in_array( 'current-menu-item', $classes, true ) ) {
$atts['aria-current'] = 'page';
}
// 有子菜单时设置 aria-hasPopup
if ( $has_children ) {
$atts['aria-haspopup'] = 'true';
$atts['aria-expanded'] = 'false';
}
$atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args, $depth );
$attrs_str = '';
foreach ( $atts as $attr => $value ) {
if ( is_scalar( $value ) && '' !== $value ) {
$attrs_str .= ' ' . $attr . '="' . esc_attr( $value ) . '"';
}
}
$title = apply_filters( 'the_title', $item->title, $item->ID );
$output .= '<a' . $attrs_str . '>';
$output .= '<span class="nav-label">' . esc_html( $title ) . '</span>';
// 有子菜单时输出展开按钮
if ( $has_children && 0 === $depth ) {
$output .= '<button class="dropdown-toggle" aria-label="打开子菜单">'
. '<svg viewBox="0 0 12 8" width="12" aria-hidden="true"><path d="M1 1l5 5 5-5" stroke="currentColor" stroke-width="2" fill="none"/></svg>'
. '</button>';
}
$output .= '</a>';
}
// 子菜单的起始标签
public function start_lvl( &$output, $depth = 0, $args = null ) {
$output .= '<ul class="dropdown-menu" role="list">';
}
// 子菜单的结束标签
public function end_lvl( &$output, $depth = 0, $args = null ) {
$output .= '</ul>';
}
}
// 使用 Walker 输出菜单
wp_nav_menu( [
'theme_location' => 'primary',
'container' => 'nav',
'container_class' => 'global-nav',
'walker' => new My_Nav_Walker(),
] );
步骤4:用 CSS 实现下拉菜单
/* 全局导航 */
.global-nav {
position: relative;
}
.nav-list {
display: flex;
align-items: center;
gap: 0;
list-style: none;
margin: 0;
padding: 0;
}
.nav-item {
position: relative;
}
.nav-item > a {
display: flex;
align-items: center;
gap: 4px;
padding: 1rem 1.25rem;
color: #1d2327;
text-decoration: none;
font-weight: 500;
font-size: 0.9rem;
transition: color 0.2s;
white-space: nowrap;
}
.nav-item > a:hover,
.nav-item.is-active > a {
color: #2271b1;
}
/* 下拉菜单 */
.dropdown-menu {
position: absolute;
top: 100%;
left: 0;
min-width: 220px;
background: #fff;
border: 1px solid #dcdcde;
border-radius: 4px;
box-shadow: 0 4px 12px rgba(0,0,0,0.12);
list-style: none;
margin: 0;
padding: 0.5rem 0;
opacity: 0;
visibility: hidden;
transform: translateY(-8px);
transition: opacity 0.2s, transform 0.2s, visibility 0.2s;
z-index: 100;
}
.nav-item.has-dropdown:hover > .dropdown-menu,
.nav-item.has-dropdown:focus-within > .dropdown-menu,
.nav-item.has-dropdown[data-open="true"] > .dropdown-menu {
opacity: 1;
visibility: visible;
transform: translateY(0);
}
.dropdown-menu li a {
display: block;
padding: 0.6rem 1.25rem;
color: #1d2327;
text-decoration: none;
font-size: 0.875rem;
transition: background 0.15s;
}
.dropdown-menu li a:hover {
background: #f0f6fc;
color: #2271b1;
}
/* 汉堡按钮 */
.hamburger-btn {
display: none;
flex-direction: column;
gap: 5px;
background: none;
border: none;
cursor: pointer;
padding: 8px;
}
.hamburger-btn span {
display: block;
width: 24px;
height: 2px;
background: #1d2327;
transition: transform 0.3s, opacity 0.3s;
}
@media (max-width: 768px) {
.hamburger-btn { display: flex; }
.nav-list {
display: none;
flex-direction: column;
position: fixed;
top: 0;
right: 0;
width: 280px;
height: 100vh;
background: #fff;
padding: 4rem 1.5rem 2rem;
box-shadow: -4px 0 20px rgba(0,0,0,0.15);
overflow-y: auto;
z-index: 1000;
}
.nav-list.is-open { display: flex; }
}
步骤5:用 JavaScript 控制汉堡菜单和下拉菜单
// js/navigation.js
(function() {
const btn = document.querySelector('.hamburger-btn');
const menu = document.getElementById('nav-list');
if (!btn || !menu) return;
// 汉堡菜单的开合
btn.addEventListener('click', function() {
const isOpen = menu.classList.toggle('is-open');
btn.setAttribute('aria-expanded', isOpen);
btn.setAttribute('aria-label', isOpen ? '关闭菜单' : '打开菜单');
document.body.style.overflow = isOpen ? 'hidden' : '';
});
// 按 ESC 键关闭
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape' && menu.classList.contains('is-open')) {
menu.classList.remove('is-open');
btn.setAttribute('aria-expanded', 'false');
document.body.style.overflow = '';
btn.focus();
}
});
// 下拉菜单的键盘操作
document.querySelectorAll('.dropdown-toggle').forEach(function(toggle) {
toggle.addEventListener('click', function(e) {
e.preventDefault();
const parent = toggle.closest('.has-dropdown');
const isOpen = parent.getAttribute('data-open') === 'true';
parent.setAttribute('data-open', !isOpen);
toggle.setAttribute('aria-expanded', !isOpen);
});
});
// 点击菜单外部时关闭
document.addEventListener('click', function(e) {
if (!menu.contains(e.target) && !btn.contains(e.target)) {
menu.classList.remove('is-open');
btn.setAttribute('aria-expanded', 'false');
document.body.style.overflow = '';
}
});
})();
注意事项
- 扩展
Walker_Nav_Menu时,务必在start_el()内调用apply_filters('nav_menu_link_attributes', ...)。插件添加链接属性时需要这个钩子。 - 为了让下拉菜单支持键盘操作和屏幕阅读器,请正确设置
aria-haspopup和aria-expanded。 - 把
wp_nav_menu()的fallback_cb设为false后,在没有设置菜单时不会输出任何内容。默认情况下会回退到wp_page_menu()。
总结
导航菜单的自定义,按“用 register_nav_menus() 注册区域→用 wp_nav_menu() 做基本输出→继承 Walker_Nav_Menu 完全控制 HTML 结构→用 CSS 实现下拉菜单和动画→用 JS 实现汉堡菜单开合并兼顾无障碍”的流程来完善。相关文章:自定义 WordPress 小工具区域的方法、在 WordPress 中实现面包屑导航的方法。
关于 WordPress 有疑问?本站运营方位于日本,仅以日语回复。 联系我们(日语)