WordPress主题自定义菜单仅显示2级,无法显示3级菜单问题咨询
WordPress自定义菜单三级层级适配方案
核心问题
现有自定义菜单函数仅做了两级菜单的逻辑判定,未识别二级菜单项下的子菜单,也没有输出三级菜单对应的DOM结构,因此只能展示两层菜单。
修改后完整菜单函数
function print_menu($menu_name){ if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ $menu_name ] ) ) { $menu = wp_get_nav_menu_object( $locations[ $menu_name ] ); $menu_items = wp_get_nav_menu_items($menu->term_id); $menu_list = ''; $count = 0; $cpi = get_the_id(); $cai = 0; foreach( $menu_items as $current ) { if($cpi == $current->object_id ){ if ( !$current->menu_item_parent ) { $cpi = $current->ID; }else{ $cpi = $current->menu_item_parent; } $cai = $current->ID; break; } } // 整理菜单父子关系映射 $items_by_parent = []; foreach ( $menu_items as $item ) { $items_by_parent[$item->menu_item_parent][] = $item; } // 递归生成多层级菜单 function build_menu($parent_id, $items_by_parent, $cpi, $cai, $level = 0) { $html = ''; if ( !isset($items_by_parent[$parent_id]) ) return $html; foreach ( $items_by_parent[$parent_id] as $item ) { $link = $item->url; $title = $item->title; $ac2 = $item->ID == $cai ? ' current_menu' : ''; $ac = $item->ID == $cpi ? ' active' : ''; $has_child = isset($items_by_parent[$item->ID]); $li_class = $level == 0 ? 'nav-item' : ''; $a_class = $level == 0 ? 'nav-link' : 'dropdown-item'; $toggle_attr = ''; if ( $has_child ) { $li_class .= ' dropdown'; $a_class .= ' dropdown-toggle'; $toggle_attr = ' role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"'; } $html .= '<li class="'.$li_class.$ac.'">'; $html .= '<a href="'.$link.'" class="'.$a_class.$ac2.'"'.$toggle_attr.'><span>'.$title.'</span></a>'; if ( $has_child ) { $html .= '<div class="dropdown-menu" aria-labelledby="navbarDropdown">'; $html .= build_menu($item->ID, $items_by_parent, $cpi, $cai, $level + 1); $html .= '</div>'; } $html .= '</li>'; } return $html; } $menu_list = build_menu(0, $items_by_parent, $cpi, $cai); } else { $menu_list = '<li>菜单 "'.$menu_name.'" 未定义</li>'; } echo $menu_list; }
配套CSS样式(适配Bootstrap框架)
如果你的主题使用Bootstrap作为前端框架,需要添加以下CSS实现三级菜单悬浮展示:
.dropdown-menu .dropdown-menu { top: 0; left: 100%; margin-top: -1px; } .dropdown:hover > .dropdown-menu { display: block; }
注意事项
- 若主题未使用Bootstrap框架,可根据自身主题的样式规则调整对应类名和下拉触发逻辑
- 菜单后台设置时需确保三级菜单项正确挂载到对应的二级父菜单项下
内容的提问来源于stack exchange,提问作者neda assareh
相关产品推荐
相关产品推荐

