wp_nav_menu – show children of current menu item only?

I am trying to create a menu structure with a simple concept:

  1. A horizontal, 1-level deep main menu
  2. A vertical submenu, that contains children of the current main menu item (2 levels deep)

Of course, the submenu should be shown in the following cases:

Read More
  1. Viewing the main menu item
  2. Viewing a direct child of the main menu item
  3. Viewing a descendant of the main menu item (3rd level)

Since I want to keep the menu clean, I need to show the 3rd level for the currently active 2nd level menu item only.

Basically, I want to achieve the same thing as described in this topic: How to show only parents subpages of current page item in vertical menu?BUT, using wp_nav_menu()

I would be happy to use filters or custom walkers if somebody could point me to a right direction.

The important thing here to notice is that since wp_nav_menu can contain also custom links or category links, the solution should work for all of those cases.

Related posts

Leave a Reply

1 comment

  1. Don’t know if this is the best way but i would go like this-

    1) Hook into wp_nav_menu_objects filter. The function will recieve a list of all menu-items. These menu items will already have the information regarding current page or current page’s ancestor(do a var_dump once)

    2) From these menu items, unset all the menu items which are not supposed to be shown & return the rest

    foreach(<loop all items>) {
    
        if(<this item's parent is current page or it's ancestor>)
            // this element should be displayed
        else
            // this element should be deleted, unset() it
    
    }
    

    3) Override the walk and/or display_element methods in the custom walker, by default the children are added inside the parent’s <li> tag, but as-per my understanding of your HTML you’ll need them seperate

    Alternatively if you’re already overriding the walk method but keeping most of it’s code in the custom walker, you can create a custom filter for the 2nd step above. This would make that loop much easier since the items will be already sorted