Appending a List of Child Pages

Back in Chapter 8, I showed you how to include a list of child pages in a page template. You could do so using a filter, so you could maintain the code in functions .php rather than individual template files.

Listing 9-24 shows how to create the child pages filter. In this case, you'll assume that the filter should operate only on single page archives; if the page content is shown as part of a Loop, you probably don't want to clutter the Loop display with a bunch of page lists.

Listing 9-24. Appending child pages using a filter function append_child_pages($content) { if (is_page()) {

global $post;

$children = '<ul>'.wp_list_pages('title_li=&child_of'=$post->ID).'</ul>';

return $content.$children;

add_filter('the_content','append_child_pages');

This is even simpler than the previous example. Again, you need the global $post object. Since wp_list_pages() prints list items without the surrounding list tags, you have to add those manually. Then you pass the content and the page list back to the Loop as one big string.

You could easily alter this function to print the child pages only if the parent page's content is empty, as shown in Listing 9-25. The changes from the previous example are in bold.

Listing 9-25. Appending child pages only if the parent page is empty function append_child_pages($content) {

global $post;

$children = '<ul>'.wp_list_pages('title_li=&child_of'=$post->ID).'</ul>';

return $content.$children;

add_filter('the_content','append_child_pages');

0 0

Post a comment