I’m building a new site and the navigation on it requires me to use a different bit of code for parent and child pages. I thought I’d share the code for those out there building a similar navigation. Here’s a handy bit of code that you can use to display all subpages on a subpage. For instance, you have your pages setup like so:

Page: Fruit

subpage: Banana

subpage: Apply

subpage: Orange

On Parent Page

If you were wanting to show a navigation menu of all subpages in the Fruit category you could use the following bit of code:

[inline]
[code lang=”php”]
<?php
$children = wp_list_pages(‘title_li=&child_of=’.$post->ID.’&echo=0′);
if ($children) { ?>
<ul id="mainNav">
<div id="locationsNavHead">choose a product</div>
<?php echo $children; ?>
</ul>
<?php } ?>
[/code]
[/inline]

On Subpages

For child, or subpages, we could use the following bit of code:

[inline]
[code lang=”php”]
<div id="sidebar">
<?php
//list subpages even if on a subpage
if($post->post_parent)
$children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0");
else
$children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0");
if ($children) { ?>
<ul id="mainNav">
<div id="locationsNavHead">choose a product</div>
<?php echo $children; ?>
</ul>
<?php } ?>
</div>
[/code]
[/inline]

If you are confused at what this all means please comment below and check out wp_list_pages() over at the WordPress Codex

Devin Walker is a San Diego-based WordPress Developer and enthusiast. He is the author of several popular and highly-rated WordPress themes and plugins. In his free time he enjoys playing Golf and traveling.

Follow Devin:

5 Responses to “WordPress List Subpages Even if On Subpage”

  1. Jorge

    Wow!!, finally i found the solution!, thanks man!

    Reply
    • Musti

      This is very useful, however I have a problem while being in certain child pages of the same parent the menu disapears; however being on other child pages of the same parent the menu is kept in its place. It is really strange, I would be glad if you could tell me what is the problem.
      Thanks in advance

      Reply
  2. Jamie

    Wow awesome! Thanks for your help!

    Reply
  3. Nyrngrs24

    How would you grab the featured image with this?

    Reply
  4. Nile Flores

    I created WP Subpages widget for that for sidebars (but it can work for sites using widgets in pages)

    Reply

Leave a Reply