Given the page id, check if it has children

I need to list subpages, given the id of parent one. I tried as follows:

if ($children = get_pages(array('child_of' => $post->ID)) && !empty($children)) {
    //Do stuff here
}

But this returns false anyways.

I tried as well get_page_children($post->ID, array), but I think I didn’t really get how this function works.

So, is it possible at all to get one page’s children? Thank you.

1 Answer
1

The example from the WP codex for get_page_children does what you are looking for with a page titled “Portfolio”:

$my_wp_query = new WP_Query();
$all_wp_pages = $my_wp_query->query(array('post_type' => 'page', 'posts_per_page' => '-1'));

// Get the page as an Object
$portfolio =  get_page_by_title('Portfolio');

// Filter through all pages and find Portfolio's children
$portfolio_children = get_page_children( $portfolio->ID, $all_wp_pages );

The first part initializes a new WP_Query, then using this is it is querying all pages and returning them as objects set to the $all_wp_pages variable.

get_page_children needs two arguments: the ID of the parent page, and the list of pages’ objects in which to look for that page’s children (the $all_wp_pages variable above).

For your example to work, you need that list of objects created by the query ($all_wp_pages) as the get_page_children doesn’t query the DB, but rather checks against that list.

So, get_page_children($post->ID, $all_wp_pages)

In full:

$page_id = $post->ID;
$my_wp_query = new WP_Query();

$all_wp_pages = $my_wp_query->query(array('post_type' => 'page', 'posts_per_page' => '-1'));

$the_pages_children = get_page_children( $page_id, $all_wp_pages );

Leave a Comment