get_page_hierarchy

Order the pages with children under parents in a flat list.

Description

(array) get_page_hierarchy( (array) &$pages, (int) $page_id = 0 ); 

It uses auxiliary structure to hold parent-children relationships and runs in O(N) complexity

Returns (array)

A list arranged by hierarchy. Children immediately follow their parents.

Parameters (2)

0. $pages (array) => &$pages
Posts array, passed by reference.
1. $page_id — Optional. (int)
Parent page ID. Default 0.

Usage

  1. if ( !function_exists( 'get_page_hierarchy' ) ) { 
  2. require_once ABSPATH . WPINC . '/post.php'; 
  3.  
  4. // Posts array, passed by reference. 
  5. $pages = array(); 
  6.  
  7. // Optional. Parent page ID. Default 0. 
  8. $page_id = -1; 
  9.  
  10. // NOTICE! Understand what this does before running. 
  11. $result = get_page_hierarchy($pages, $page_id); 
  12.  

Defined (1)

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

/wp-includes/post.php  
  1. function get_page_hierarchy( &$pages, $page_id = 0 ) { 
  2. if ( empty( $pages ) ) { 
  3. return array(); 
  4.  
  5. $children = array(); 
  6. foreach ( (array) $pages as $p ) { 
  7. $parent_id = intval( $p->post_parent ); 
  8. $children[ $parent_id ][] = $p; 
  9.  
  10. $result = array(); 
  11. _page_traverse_name( $page_id, $children, $result ); 
  12.  
  13. return $result;