get_page_hierarchy()WP 2.0.0

Sorts an array of hierarchical posts based on parent relationships (post_parent).

As a result, child posts are placed after parent posts. It will return a trimmed sorted array.

In WP, this function is used to build URLs for hierarchical posts. However, there are situations when it can be useful for other purposes.

Despite the fact that the first parameter is passed by reference, the passed value does not change in any way. Apparently, this is legacy.

1 time — 0.000018 sec (very fast) | 50000 times — 0.18 sec (very fast) | PHP 7.0.8, WP 4.6

No Hooks.

Returns

String[]. An array where elements are sorted in a tree - the child element is located after the parent.

The array contains the post ID as the key and the post slug as the value.

Array
(
	[54] => no-parents
	[87] => parent-page
	[97] => child-1
	[32] => child-2
)

Usage

get_page_hierarchy( $pages, $page_id );
& $pages(array) (required)

An array of hierarchical post objects that need to be sorted in a tree.

The parameter is passed by reference, but does not change inside. Apparently due to legacy.

$page_id(number)
The ID of the parent post (page).
Default: 0

Examples

0

#1 Tree sorting demonstration

To make it clearer, I removed most of the fields that each post has. There are 3 fields involved in this sorting: ID, post_parent, and post_name.

So what does the function do? As you can see from the example, we had an array of posts where one post is a child of another. But the order of these posts in the array is chaotic.

This function sorts all the elements in the array so that each next element is a child of the previous one. After that, the function creates a new array and puts the posts ID in the key of this array, and the posts slug (post_name) is placed in the value. As a result, we can easily create a tree of posts using the resulting array...

$pages = array(
  (object) array(
	 'ID'            => 111,
	 'post_name'     => 'no-parents',
	 'post_parent'   => 0,
  ),
  (object) array(
	 'ID'            => 222,
	 'post_name'     => 'child-1',
	 'post_parent'   => 444,
  ),
  (object) array(
	 'ID'            => 333,
	 'post_name'     => 'child-2',
	 'post_parent'   => 444,
  ),
  (object) array(
	 'ID'            => 444,
	 'post_name'     => 'parent-page',
	 'post_parent'   => 111,
  ),
);

$pages = get_page_hierarchy( $pages );

/* $pages will be equal to:
Array
(
	[111] => no-parents
	[444] => parent-page
	[222] => child-1
	[333] => child-2
)
*/

Changelog

Since 2.0.0 Introduced.

get_page_hierarchy() code WP 6.8.3

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;
}