Using WordPress ‘get_page_children()’ PHP function

The get_page_children() WordPress PHP function identifies descendants of a given page ID in a list of page objects.

Usage

To use get_page_children(), provide the page ID and an array of WP_Post objects:

$descendants = get_page_children($page_id, $pages);

Parameters

  • $page_id (int) – Required. The page ID for which to find descendants.
  • $pages (array of WP_Post objects) – Required. List of page objects from which descendants should be identified.

More information

See WordPress Developer Resources: get_page_children()

Examples

Find children of a specific page by title

Find the child pages of a page titled “Portfolio”:

// Set up the objects needed
$my_wp_query = new WP_Query();
$all_wp_pages = $my_wp_query->query(array('post_type' => 'page'));

// 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);

// Output the result
echo '<pre>' . print_r($portfolio_children, true) . '</pre>';

Find children of a custom post type

Find child posts of a custom post type called “locations”:

$location_parent_id = /* Parent Location ID */;

// Query the locations post type
$all_locations = get_pages(array(
    'post_type' => 'locations',
    'post_status' => array('publish', 'pending')
));

// Find the children of the parent location
$inherited_locations = get_page_children($location_parent_id, $all_locations);

// Output the result
echo '<pre>' . print_r($inherited_locations, true) . '</pre>';

Find children of a page with a specific ID

$page_id = 42;
$all_wp_pages = get_pages();

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

// Output the result
foreach ($children as $child) {
    echo $child->post_title . '<br>';
}

Retrieve grandchildren of a specific page

$parent_page_id = 123;
$all_wp_pages = get_pages();

$children = get_page_children($parent_page_id, $all_wp_pages);
$grandchildren = array();

foreach ($children as $child) {
    $grandchildren = array_merge($grandchildren, get_page_children($child->ID, $all_wp_pages));
}

// Output the result
foreach ($grandchildren as $grandchild) {
    echo $grandchild->post_title . '<br>';
}

Find and display all descendants of a specific page

function get_all_descendants($page_id, $pages) {
    $descendants = get_page_children($page_id, $pages);
    foreach ($descendants as $descendant) {
        $descendants = array_merge($descendants, get_all_descendants($descendant->ID, $pages));
    }
    return $descendants;
}

$parent_page_id = 987;
$all_wp_pages = get_pages();

$all_descendants = get_all_descendants($parent_page_id, $all_wp_pages);

// Output the result
foreach ($all_descendants as $descendant) {
    echo $descendant->post_title . '<br>';
}