Get Child Pages List In Wordpress

10th May 2010

It is possible to print out a list of pages in Wordpress, but these functions are designed to print from the root pages to a certain level. I often need to print out a list of pages that are children of the current page being looked at so I created the following function.

  1. /**
  2.  * Get a list of child pages.
  3.  *
  4.  * @param integer $id The ID of the parent page.
  5.  *
  6.  * @return string The list of child pages.
  7.  */
  8. function getChildPagesList($id)
  9. {
  10. // Get the child pages of the current page.
  11. $args = array(
  12. 'child_of' => $id,
  13. 'echo' => 0,
  14. );
  15. $pages = get_pages($args);
  16.  
  17. // Build the page list
  18. $class = '';
  19.  
  20. $option = '<ul>';
  21.  
  22. foreach ($pages as $pagg) {
  23. if (is_page($pagg->ID)) {
  24. $class = ' class="on"';
  25. }
  26. $option .= '<li' . $class . '>';
  27. $option .= '<a href="' . get_page_link($pagg->ID) . '" title="' . $pagg->post_title . '">' . $pagg->post_title . '</a>';
  28. $option .= '</li>';
  29. $class = '';
  30. }
  31.  
  32. $option .= '</ul>';
  33.  
  34. // Return list
  35. return $option;
  36. }

 

This function works by calling the get_pages() function in order to retrieve the pages that are children to this page. The echo argument is also used and given a 0 to make the function return the array of pages rather than just print them out. To use this function create some pages that have children and pick a page (in this instance page ID 29) you want to print out like this.

print getChildPagesList(29);

To print out the pages connected to the current post use the following:

echo getChildPagesList($post->ID);

 

Comments

Permalink

Couldn't you use wp_list_pages with the 'child_of' parameter included?

So the equivalent examples would be:

wp_list_pages('child_of=29');

wp_list_pages('child_of='.$post->ID);

and you can also choose whether or not to print out the returned pages with the argument 'echo=1' or 'echo=0'.

Rik (Sun, 06/13/2010 - 14:13)

Permalink

You are quite right, wp_list_pages() would do the job just as well. I'm sure there was a very good reason that I created this function, although I'm not sure what it was now. :)

philipnorton42 (Sun, 06/13/2010 - 15:52)

Add new comment

The content of this field is kept private and will not be shown publicly.