Show a List of Child Pages without Altering Templates

If you have a list of child pages, you may want to show them whenever someone visits the parent page. Several solutions on the net involve making modifications to your theme template, or even creating a new template page. Some even recommend installing a plugin. But none of these solutions appeal to me. I don’t like modifying theme files, and I don’t like installing plugins. So here’s a quick way to show a list of child pages in WordPress using a “plug-n-play” solution that works like a charm.

Step 1: Create your Page Hierarchy

In the screenshot below, I have a set of child pages under the main “Parent Page”.

page-structure

I’ve also created an “additional” child page starting with an “A”. You’ll see later on why.

Step 2: Insert Code into functions.php

Open up your theme functions.php or custom plugin and add the following code.

function list_child_posts( $atts ) {
    global $id;
    wp_list_pages( array(
        'title_li'    => '',
        'child_of'    => $id,
        'sort_column' => 'post_date',
        'sort_order' => 'desc',
    ) );
}
add_shortcode( 'list_children', 'list_child_posts' );

If you don’t know how to add code to your WordPress installation, read my earlier tutorial on the same. This snippet creates a “shortcode” that we can use in our parent theme to display the list of child pages.

Step 3: Use the Shortcode in the Parent Page

Open your parent page for editing, and use the [list_children] shortcode as shown in the screenshot here:

 

insert-shortcode

Now when you view the parent page in your browser, you’ll see a list of all the child pages sorted by date of publication:

List of Child Pages sorted by post date

Step 4: Sort the List of Child Pages

By default, the function wp_list_pages sorts the pages alphabetically. This is probably not what we want. In the code snippet above, I passed an argument to sort by the post date instead. This is the relevant line of code:

'sort_column' => 'post_date',

You can use the “sort_column” parameter to arrange the posts by modification date, the author, or even make it random. You can see the full documentation of wp_list_pages here.

However, the documentation does not tell you that you can reverse the sorting order if desired. So if you want to show the list of child pages in reverse chronological order, you just need to add the following line to the list of arguments:

'sort_order' => 'desc',

This will give the following result:

reverse-sort

So if you want your visitors to get a complete list of child pages whenever the view a parent page, simply use the above shortcode to get it done. No changing page templates, no theme modifications, and no plugins!

Speak Your Mind

*