Get Child Pages List In Wordpress

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.

/**
 * Get a list of child pages.
 *
 * @param integer $id         The ID of the parent page.
 *
 * @return string The list of child pages.
 */
function getChildPagesList($id)
{
    // Get the child pages of the current page.
    $args = array(
                    'child_of' => $id,
                    'echo'     => 0,
                 );
    $pages = get_pages($args);

    // Build the page list
    $class = '';

    $option = '<ul>';

    foreach ($pages as $pagg) {
        if (is_page($pagg->ID)) {
            $class = ' class="on"';
        }
        $option .= '<li' . $class . '>';
        $option .= '<a href="' . get_page_link($pagg->ID) . '" title="' . $pagg->post_title . '">' . $pagg->post_title . '</a>';
        $option .= '</li>';
        $class = '';
    }

    $option .= '</ul>';

    // Return list
    return $option;
}

 

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

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'.

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. :)

Name
Philip Norton
Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
8 + 9 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.