Sillybean

Listing child pages

The Codex offers a way to list the children of the current page by adding this to your theme:

<?php
$children = wp_list_pages('title_li=&child_of='.$post->ID.'&echo=0');
if ($children) { ?>
<ul>
  <?php echo $children; ?>
</ul>
<?php } ?>

… or listing the siblings of the currently viewed child page:

<?php
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>
  <?php echo $children; ?>
</ul>
<?php } ?>

However, if you don’t want to include the code in your template file, you can use the shortcodes plugin for listing pages and child pages.

The above code can be expanded in a number of ways….

Example: excerpts of top-level pages with linked subpages

Here, we want to show excerpts from our top level pages, and under that, a list of the subpages. We need PJW Page Excerpt to enable excerpts for pages.

<?php
$pages = get_posts('post_type=page&orderby=menu_order&order=ASC&post_parent=1200&posts_per_page=-1');
foreach($pages as $post) : ?>
<div class='post' id='<?php echo $post->post_name; ?>'>
<h2><a href='<?php the_permalink(); ?>' title='<?php the_title(); ?>'><?php the_title(); ?></a></h2>
<p><?php the_excerpt(); ?></p>
<?php
$children = wp_list_pages('title_li=&child_of='.$post->ID.'&echo=0&depth=1');
if ($children) { ?>
<ul class='subnav'>
    <?php echo $children; ?>
  </ul>
<?php } ?>
</div>
<!-- .post -->
<?php endforeach; ?>

Example: table of contents

In this example, we want to display a table of contents for all the children and grandchildren of page #1200:

<?php
$pages = get_posts('post_type=page&orderby=menu_order&order=ASC&post_parent=1200&posts_per_page=-1');
foreach($pages as $post) : ?>
<ol class='post' id='<?php echo $post->post_name; ?>'>
<li><a href='<?php the_permalink(); ?>' title='<?php the_title(); ?>'><?php the_title(); ?></a>
      <?php
      $children = wp_list_pages('title_li=&child_of='.$post->ID.'&echo=0&depth=1');
      if ($children) { ?>
<ul class='subnav'>
          <?php echo $children; ?>
        </ul>
     <?php } ?>
    </li>
</ol>
<?php endforeach; ?>

Posted on August 9, 2009 at 9:15 am in WordPress · 2 comments

Sharing this post? The short URL is: http://sillybean.net/?p=2704

2 Responses to “Listing child pages”

  1. Brian says:

    Thanks for the post. Can you recommend a solution for merging the first two code samples? My intention is to show the children as well as the siblings of any given page.

  2. Brian, I’m sorry I overlooked your comment last month. Did you figure it out?

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>