rss

Displaying child pages of the current page

8 Apr, 2008 MarkB Navigation

A prime feature of most CMS systems is that pages have a strong hierarchy – plenty of pages, sub-pages and sub-sub-sub pages. Depending on exactly what you want to accomplish, there’s a main means of doing this that will help you have a nicely dynamic navigation area.

At first glance

wp_list_pages('title_li=&child_of='.$post->ID);

…would be an option, except that when you end up on a child page, the list disappears because the current page no longer has any children.

Enter the solution:

<?
if(wp_list_pages('child_of='.$post->ID.'&echo=0&exclude=2')) {
echo "<ul>";
wp_list_pages('title_li=&child_of='.$post->ID.'&exclude=2');
echo "</ul>";
}
elseif(get_the_title($post->post_parent) != the_title(' ' , ' ',false)) {
echo "<ul>";
wp_list_pages('child_of='.$post->post_parent.'&title_li=&exclude=2');
echo "</ul>";
} ?>

What this does is:

  • Generate a list of sibling pages if there are no child pages present
  • If there are child pages, they’ll be shown

This is really useful for creating a dynamic navigation that constantly allows users to move to other pages on the site and will also allow your client or the end user to create pages and sub pages freely without having to worry about digging through code to update the navigation area.

2 Comments

  1. I have been searching for hours for code like this.

    It’s almost what I want.

    Could you please show the modification to show this code only on pages that have child pages?

    Right now it shows on every page.

    Thanks
    David

  2. Hi David

    The plugin will display child pages whenever there are child pages to display. If there are no child pages, then nothing will display…

    This is how it works for me anyways?

Leave a Reply

About The WordPress Guru

Over the last 4 or 5 years, I’ve been digging into the Wonders of WordPress. From the days when the Classic theme was the shizz until now, WordPress has gone from strength to strength both as the blogging platform of choice for many big players and as a CMS with...

Learn more »