You are here:
  1. Home
  2. Blog
  3. Geek
  4. Wordpress Child Pages Page... or something

WordPress Child Pages Page… or something

 |  Geek, PHP

OK, back to srs business posts now…

One of my current top secret projects (it’s not that exciting, I’m just helping someone convert their site to WordPress) involves creating pages with a list of child pages on ’em. Back in ye olde days I’d have done this manually (which meant every time a child page was added the parent had to be modified) or farted about with SQL queries but Modern Day WordPress seems to have a function for everything and so it’s much simpler. So, without further ado…

Create the template:

<?php
/*
Template Name: Sub Page
*/
?>

<?php get_header(); ?>

<div id="content">

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

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

	if ($post->post_parent)
		echo '<a href="'. get_permalink($post->post_parent) .'">&laquo; Back to '. get_the_title($post->post_parent) .'</a>';
?>


</div>

<?php get_sidebar(); ?>

<?php get_footer(); ?>

Save it as subpage.php, upload it to your theme directory and then whenever you just want a list of sub (child) pages, select Sub Page from the Template dropdown on the right. Ner nerrr!

Tip: if you wanted a section intro instead of just a list of links, bung <?php if ( have_posts() ) { while ( have_posts() ) { the_post(); ?><?php the_content(); ?><?php } } ?> after the h2 title stuff.

Jem Turner jem@jemjabella.co.uk +44(0)7521056376

9 comments so far

  1. Kalliste said:

    Ha! I was thinking "Oh neat! I always wanted to know how to do that" and all the other commenters are like "Uh, Jem, we already knew that". Hee, I think we’re both behind the ball… except you have an excuse considering you don’t actually use WP :D

  2. Vera said:

    Whoa! THANKS! I’ve been sooo ready to make some uber "complex" sql query for this (in my new theme which might make it online sometime this centrury). :B
    My googling skills fail *sniffles*

  3. Jem said:

    @Kalliste: I’ve known about listing child pages for quite a while, it just took me some time to put Templates and the child page listing together. It was definitely one of those "D’OH! Why didn’t I do this years ago?" moments.

  4. Mallory said:

    Good job, Jem! You finally figured out what I learnt way back in 2008 when I was still a WordPress n00b!

    LOL, I jest, I jest … The first time I read this entry, I couldn’t believe that I learnt something about coding before you did!

    In fact, I thought I was reading incorrectly at first, but once I confirmed that I was right, I couldn’t resist the chance to act a bit like my former online persona. :P

Follow on Instagram