get_page_hierarchy() WordPress Function

The get_page_hierarchy() function will return an array of all the pages on a WordPress site, organized by parent and child pages. This is helpful for creating a navigation menu or for display purposes.

get_page_hierarchy( WP_Post[] $pages, int $page_id ) #

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


Description

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


Top ↑

Parameters

$pages

(WP_Post[])(Required)Posts array (passed by reference).

$page_id

(int)(Optional) Parent page ID. Default 0.


Top ↑

Return

(string[]) Array of post names keyed by ID and arranged by hierarchy. Children immediately follow their parents.


Top ↑

Source

File: wp-includes/post.php

function get_page_hierarchy( &$pages, $page_id = 0 ) {
	if ( empty( $pages ) ) {
		return array();
	}

	$children = array();
	foreach ( (array) $pages as $p ) {
		$parent_id                = (int) $p->post_parent;
		$children[ $parent_id ][] = $p;
	}

	$result = array();
	_page_traverse_name( $page_id, $children, $result );

	return $result;
}


Top ↑

Changelog

Changelog
VersionDescription
2.0.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More
Show More