Showing Sub Pages in WordPress


May 19th, 2009

WordPress allows site owners to create “Pages”, in addition to normal blog posts. Pages are simply static content. Most WordPress blogs at the very least have some sort of “About” page, but it’s possible to deeply nest pages and create a rich hierarchy.

Depending on your chosen theme, this hierarchy is (by default) shown on the sidebar. However, that can get unwieldy if you have a complex site structure. One approach I sometimes take is to limit the hierarchy on the sidebar, but display links to the sub-pages on each of the main pages. What do I mean?

Suppose I have arranged my pages as follows (using Permalinks of course!)

  • About Me
    • My Career
      • Resume
    • My Hobbies

Normally, the content section of the About page would look something like this:

About Me

Posted by Ryan Thompson

Content…

But, with just a little template magic, we can tell WordPress to show all of the subpages of the current page.

In your WordPress admin page, click on Appearance -> Editor, and then find the Page Template (page.php) on the right hand side of the page. Then, look for a line like this:

<h2><?php the_title(); ?></h2>

After that line (or wherever you would like the sub pages to appear), add the following line:

<ul><?php wp_list_pages('title_li=Sub%20Topics:&depth=4&child_of=' . get_the_ID()); ?></ul>

Now, your page will look something like this:

About Me

  • Sub Topics:
    • My Career
      • Resume
    • My Hobbies

Posted by Ryan Thompson

Content…

The sub-pages (and the “Sub Topics:” heading) will only display if the page actually has sub-pages, so it is safe to use this code on all pages.

The important bit is the wp_list_pages() call, and the use of get_the_ID() to retrieve the current numeric page ID.

Once you have your sub pages displaying correctly, you’re of course free to apply a style to the unordered list (<ul class=”…”>) to render this particular list in a more imaginative format, assuming you have some HTML/CSS know-how.

One Response to “Showing Sub Pages in WordPress”

  1. Mike Says:

    Hi, nice posts there :-) thank’s for the interesting information