Displaying Subpages while on Parent page?

I would like to create a navigation menu where I will be displaying two level pages.

To illustrate that:

Read More
  • Parent 1
  • Parent 2
  • Parent 3 (current)
    • Child 1
    • Child 2
    • Child 3
  • Parent 4

So I would like to display all the parent pages in my navigation container but only display children pages when the user is currently on its parent page.

Related posts

Leave a Reply

1 comment

  1. This is pretty easy, as WordPress sets css classes for the parent pages.
    Default we hide all sublists (ul) from the menu with

    .menu ul {
        display: none;
    }
    

    Then when the parent page is selected we use the css classes that are set by WordPress to show the sublists again.

    .menu .current_page_ancestor, .menu .current_page_parent {
        display: block;
    }
    

    So all you need is this in your template

    Template:

    <ul class="menu">
        <?php wp_list_pages('title_li=') ?>
    </ul>
    

    and this in your css file.

    CSS:

    .menu ul {
        display: none;
    }
    
    .menu .current_page_ancestor > ul, .menu .current_page_parent > ul {
        display: block;
    }