get_page_children()
Identify descendants of a given page ID in a list of page objects.
Descendants are identified from the $pages array passed to the function. No database queries are performed.
No Hooks.
Return
WP_Post[]
. List of page children.
Usage
get_page_children( $page_id, $pages );
- $page_id(int) (required)
- Page ID.
- $pages(WP_Post[]) (required)
- List of page objects from which descendants should be identified.
Examples
#1 Leave only the children to Portfolio page
// Get all the pages to be searched. $all_pages = ( new WP_Query() )->query( [ 'post_type' => 'page', 'posts_per_page' => -1 ] ); // the page whose children you want to get $about_id = 7; // let's leave only the children to Portfolio $about_childrens = get_page_children( $about_id, $all_pages ); // let's simplify the output foreach( $about_childrens as & $page ){ unset( $page->post_content, $page->post_date_gmt, $page->post_password, $page->post_modified_gmt, $page->post_content_filtered, $page->post_mime_type ); } //result print_r( $about_childrens );
We get it:
Array ( [0] => WP_Post Object ( [ID] => 10124 [post_author] => 12 [post_date] => 2018-05-19 08:11:19 [post_title] => Privacy Policy [post_excerpt] => [post_status] => publish [comment_status] => closed [ping_status] => closed [post_name] => privacy-policy [to_ping] => [pinged] => [post_modified] => 2018-09-12 05:28:35 [post_parent] => 7 [guid] => /about/privacy-policy [menu_order] => 3 [post_type] => page [comment_count] => 0 [filter] => raw ) [1] => WP_Post Object ( [ID] => 9976 [post_author] => 12 [post_date] => 2018-05-05 01:01:09 [post_title] => Active users [post_excerpt] => [post_status] => publish [comment_status] => closed [ping_status] => open [post_name] => best-users [to_ping] => [pinged] => [post_modified] => 2018-05-05 02:04:25 [post_parent] => 7 [guid] => /about/best-users [menu_order] => 2 [post_type] => page [comment_count] => 0 [filter] => raw ) [2] => WP_Post Object( ... ) [3] => WP_Post Object( ... ) )
#2 Leave only the children posts (for the CPT)
Let's get all posts of locations
CPT and leave only children of post 12:
$location_parent_id = 12; // Instead of calling and passing query parameter differently, we're doing it exclusively $all_locations = get_pages( [ 'post_type' => 'locations', 'post_status' => 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 echo '' . print_r( $inherited_locations, true ) . '';
Changelog
Since 1.5.1 | Introduced. |