WordPress Tips & Tricks: How to create a sub page navigation.

Until the release of WordPress 3.0 due out later in the year, creating a sub navigation is still a somewhat obscure and tricky task. To hopefully shed some light on how to create a Sub Navigation for your own needs I am going to walk-through how you can output a pages child or sub pages. In simple terms how to display a second level navigation in your sidebar.

How to get Sub Pages

In WordPress the easiest way to get the a page’s child pages is to use the get_pages function. This function allows you to specify that you want the children of a page by using the child_of and parent parameters. When called this function returns an array that you can utilize to iterate over and output the child pages.

$child_pages = get_pages('child_of='. $post->ID; . '&parent=' . $post->ID;);

The $post variable is used in WordPress templates to denote the current post or page. We utilize the ID property to specify we want returned all pages that are children of the current page.

How to output the pages in a list

To output a list of the sub pages we can iterate over the children and output the page titles and links in a list by using the get_page_link function and the ID and post_title properties of the returned Page object.

echo '';

The full example

Using the above code we will be executing the code on all website pages including posts and categories. To limit the execution to only pages we can utilize the is_page function. As we want to display the secondary navigation when we are on the parent page or child page we will need to check the current page to determine if we are on a root page or child page by using the post_parent property. Using this we can determine if we need to get the children of the current page or the children of the page’s parent. Doing so allows us to consistently output a Sub Page Navigation as can be seen here.

if( is_page() ) {
    $the_ID = $post->ID;
    $i_page = $post;
    if( $post->post_parent ) {
       $the_ID = $post->post_parent;
       $i_page = get_page($the_ID);
    }

    $child_pages = get_pages('child_of='. $the_ID . '&parent=' . $the_ID);

    if( count($child_pages) > 0 ) {
        echo '
  • ' . $i_page->post_title . '

  • '; } }

    Comments & Questions

    Add Your Comment