How to: Display subpages using WordPress shortcode


I wanted a way to quickly display a list of all the subpages (children) for any given page within a WordPress site easily and effectively using the least amount of code.

By adding the following code into your themes functions.php file and simply adding the shortcode [listChildren] into the page content where you want your list of subpages displayed, you’ll have all the children pages for that particular page shown in correct hierarchy which is another great navigational aid for your website visitors.

<?PHP

add_shortcode('listChildren', 'wp_list_children');

function wp_list_children(){
	global $post;
	$children = wp_list_pages('title_li=&child_of='.$post->ID.'&echo=0');
	if($children)
		return "<p><strong>Browse our options</strong></p><ul>".$children."</ul>";
}

?>

By utilising the built-in WordPress function wp_list_pages, you can quickly show a list of all the sub pages for any particular page within your site.

NOTE: To make sure the list is displayed where you place the shortcode you need to return the results and not print or echo it within the function itself otherwise it will always appear at the top of the page.