Paulund
2014-10-07 #wordpress

Display Submenu Only On Parent Page

The in-built WordPress menu system allows the content author to create a menu by a simple drag n drop interface, it allows you to select existing posts, page or let you create custom links to add to the menu. Using the drag n drop interface you can select child elements on the menu. When you output the menu on your theme using the function wp_nav_menu() WordPress will automatically create the HTML for the menu and the sub-menu on your theme allowing you to easily create a menu link this.

  • Parent 1
  • Parent 2
    • Child 1
    • Child 2
  • Parent 3
    • Child A
    • Child B

When WordPress automatically creates the HTML for you it will also add the CSS classes that you can use in your theme, something similar to below.

<ul id="navbar-1" class="menu">
    <li id="menu-item-1" class="menu-item menu-item-type-post_type menu-item-object-page firstmenuitem"><a href="">Parent 1</a></li>
    <li id="menu-item-2" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children"><a href="">Parent 2</a>
    <ul class="sub-menu">
        <li id="menu-item-3" class="menu-item menu-item-type-post_type menu-item-object-page"><a href="">Child 1</a></li>
        <li id="menu-item-4" class="menu-item menu-item-type-post_type menu-item-object-page"><a href="">Child 2</a></li>
        <li id="menu-item-5" class="menu-item menu-item-type-post_type menu-item-object-page"><a href="">Child 3</a></li>
    </ul>
    </li>
    <li id="menu-item-6" class="menu-item menu-item-type-post_type menu-item-object-page"><a href="">Parent 3</a></li>
    <li id="menu-item-7" class="menu-item menu-item-type-post_type menu-item-object-page"><a href="">Parent 4</a></li>
</ul>

In this example we want the Child sub-menu to be display when you are on the Parent 2 page and hidden on all the other pages. Because of the automatic CSS classes that are added to WordPress we can simply use CSS to make sure the menu is hidden on all pages apart from the Parent page. First we need to hide the sub-menu on all pages.


.menu .sub-menu 
{ 
    display: none; 
}

When WordPress is on a page that is on the menu it will add a new CSS class to the parent item called current-menu-item. We can then use this class to display the sub-menu when you are on the correct page.


.menu .current-menu-item .sub-menu 
{ 
    display:block; 
}

.menu .current-menu-ancestor .sub-menu 
{ 
    display:block; 
}