get_page_children( int $page_id, WP_Post[] $pages ): WP_Post[]

Identifies descendants of a given page ID in a list of page objects.

Description

Descendants are identified from the $pages array passed to the function. No database queries are performed.

Parameters

$page_idintrequired
Page ID.
$pagesWP_Post[]required
List of page objects from which descendants should be identified.

Return

WP_Post[] List of page children.

More Information

This function calls itself recursively.

Source


$found_id = 0;
foreach ( (array) $pages as $page ) {
	if ( $page->post_name === $revparts[0] ) {
		$count = 0;
		$p     = $page;

		/*
		 * Loop through the given path parts from right to left,
		 * ensuring each matches the post ancestry.
		 */
		while ( 0 !== (int) $p->post_parent && isset( $pages[ $p->post_parent ] ) ) {
			++$count;
			$parent = $pages[ $p->post_parent ];
			if ( ! isset( $revparts[ $count ] ) || $parent->post_name !== $revparts[ $count ] ) {
				break;
			}
			$p = $parent;
		}

		if ( 0 === (int) $p->post_parent
			&& count( $revparts ) === $count + 1
			&& $p->post_name === $revparts[ $count ]
		) {
			$found_id = $page->ID;
			if ( $page->post_type === $post_type ) {
				break;
			}

Changelog

VersionDescription
1.5.1Introduced.

User Contributed Notes

  1. Skip to note 3 content

    Examples

    <?php
    // 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 );
    
    // echo what we get back from WP to the browser
    echo '<pre>' . print_r( $portfolio_children, true ) . '</pre>';
    ?>
  2. Skip to note 4 content

    In one of my Hierarchical Custom Post Type (locations) I did @bhlarsen’s method, and in some extent it’s returning false children. So I did it my way:

    ID;
    
    //Instead of calling and passing query parameter differently, we're doing it exclusively
    $all_locations = get_pages( array(
                            'post_type'         =&gt; 'locations', //here's my CPT
                            'post_status'       =&gt; array( 'publish', 'pending' ) //my custom choice
                        ) );
    
    //Using the function
    $inherited_locations = get_page_children( $location_parent_id, $all_locations );
    
    // echo what we get back from WP to the browser (@bhlarsen's part :) )
    echo '' . print_r( $inherited_locations, true ) . '';
    ?&gt;

    It’s giving me the correct children.

You must log in before being able to contribute a note or feedback.