get_page_children

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

Description

(array) get_page_children( (int) $page_id, (array) $pages ); 

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

Returns (array)

List of page children.

Parameters (2)

0. $page_id (int)
The page id.
1. $pages (array)
List of page objects from which descendants should be identified.

Usage

  1. if ( !function_exists( 'get_page_children' ) ) { 
  2. require_once ABSPATH . WPINC . '/post.php'; 
  3.  
  4. // The page id. 
  5. $page_id = -1; 
  6.  
  7. // List of page objects from which descendants should be identified. 
  8. $pages = array(); 
  9.  
  10. // NOTICE! Understand what this does before running. 
  11. $result = get_page_children($page_id, $pages); 
  12.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/post.php  
  1. function get_page_children( $page_id, $pages ) { 
  2. // Build a hash of ID -> children. 
  3. $children = array(); 
  4. foreach ( (array) $pages as $page ) { 
  5. $children[ intval( $page->post_parent ) ][] = $page; 
  6.  
  7. $page_list = array(); 
  8.  
  9. // Start the search by looking at immediate children. 
  10. if ( isset( $children[ $page_id ] ) ) { 
  11. // Always start at the end of the stack in order to preserve original `$pages` order. 
  12. $to_look = array_reverse( $children[ $page_id ] ); 
  13.  
  14. while ( $to_look ) { 
  15. $p = array_pop( $to_look ); 
  16. $page_list[] = $p; 
  17. if ( isset( $children[ $p->ID ] ) ) { 
  18. foreach ( array_reverse( $children[ $p->ID ] ) as $child ) { 
  19. // Append to the `$to_look` stack to descend the tree. 
  20. $to_look[] = $child; 
  21.  
  22. return $page_list;