I have searched and cannot find a custom “Walker” class that will hide the submenus from wp_nav_menu until you are on the parent page. I have found lots of ways to hide them or just show the submenus but not a way to only show submenus when you are in that section. Below is an example of how I need it to display:
Wp_nav_menu structure as it currently stands:
- Parent 1
- Parent 2
- Child 1
- Child 2
- Parent 3
- Child A
- Child B
-Display-
On Parent 1 / Homepage:
- Parent 1
- Parent 2
- Parent 3
On Parent 2 and Parent 2 child pages:
- Parent 1
- Parent 2
- Child 1
- Child 2
- Parent 3
You don’t need a custom walker to do this, it can be done using the CSS classes, and display:none;
e.g. you could start with:
With a few additional rules, based on the classes applied to the body tag you could conditionally show and hide other menu items, using classes added to the menu items via the backend.
In my opinion using CSS to ‘hide’ the unwanted menu levels is cumbersome at best, a bit ‘hacky’ at worst. Personally I never like to output anything to the page that shouldn’t be there (when it can be avoided anyways).
WordPress doesn’t currently do us any favors as they do not offer an option built into wp_nav_menu to limit the starting depth of the menu.
I have tried different walkers, widgets, and plugins to solve this issue but I have never been very happy with the solutions I’ve tried. For instance the solution in the plugin above requires that you pass the ID of the desired submenu.
I have written my own plugin which extends wp_nav_menu to add a ‘start_depth’ option. This works automatically on any subpage without having to specify anything.
Just use the code like this after installing the plugin:
for anyone interested it is available at my website: https://mattkeys.me/products/wp-nav-plus/
The answer above is correct – you can do this with css, but the menu is technically still “there”. If you would like to eliminate in completely – you can use a plugin I wrote – here.
Please rate and confirm that it works – I just released it a few days ago. I have used it on several sites already. My first plugin 🙂