The get_page_hierarchy() WordPress PHP function orders the pages with children under parents in a flat list.
Usage
$page_hierarchy = get_page_hierarchy( $pages, $page_id = 0 );
Parameters
$pages (WP_Post)
: Required. The posts array (passed by reference).$page_id (int)
: Optional. Parent page ID. Default is 0.
More information
See WordPress Developer Resources: get_page_hierarchy()
Examples
Get Page Hierarchy for All Pages
This example retrieves all pages and generates a page hierarchy.
// Get all pages $all_pages = get_pages(); // Generate the page hierarchy $page_hierarchy = get_page_hierarchy($all_pages);
Get Page Hierarchy for Specific Parent Page
This example retrieves all pages and generates a page hierarchy for a specific parent page with ID 5.
// Get all pages $all_pages = get_pages(); // Generate the page hierarchy for the parent page with ID 5 $page_hierarchy = get_page_hierarchy($all_pages, 5);
Display Page Hierarchy
This example displays the page hierarchy in a simple unordered list.
// Get all pages $all_pages = get_pages(); // Generate the page hierarchy $page_hierarchy = get_page_hierarchy($all_pages); // Display the page hierarchy echo '<ul>'; foreach ($page_hierarchy as $page_id => $page_title) { echo '<li>' . $page_title . '</li>'; } echo '</ul>';
Display Page Hierarchy with Links
This example displays the page hierarchy with links to each page.
// Get all pages $all_pages = get_pages(); // Generate the page hierarchy $page_hierarchy = get_page_hierarchy($all_pages); // Display the page hierarchy with links echo '<ul>'; foreach ($page_hierarchy as $page_id => $page_title) { $page_link = get_permalink($page_id); echo '<li><a href="' . $page_link . '">' . $page_title . '</a></li>'; } echo '</ul>';
Get Page Hierarchy and Exclude a Page
This example retrieves all pages, excluding a page with ID 3, and generates a page hierarchy.
// Get all pages excluding a page with ID 3 $all_pages = get_pages(array('exclude' => array(3))); // Generate the page hierarchy $page_hierarchy = get_page_hierarchy($all_pages);