get_page_children() WordPress Function

The get_page_children() function is a handy little function that allows you to retreive all the child pages of a given page. This can be useful for creating menus or lists of pages, or for custom queries.

get_page_children( int $page_id, array $pages ) #

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


Description

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


Top ↑

Parameters

$page_id

(int)(Required)Page ID.

$pages

(array)(Required)List of page objects from which descendants should be identified.


Top ↑

Return

(array) List of page children.


Top ↑

More Information

This function calls itself recursively.


Top ↑

Source

File: wp-includes/post.php

function get_page_children( $page_id, $pages ) {
	// Build a hash of ID -> children.
	$children = array();
	foreach ( (array) $pages as $page ) {
		$children[ (int) $page->post_parent ][] = $page;
	}

	$page_list = array();

	// Start the search by looking at immediate children.
	if ( isset( $children[ $page_id ] ) ) {
		// Always start at the end of the stack in order to preserve original `$pages` order.
		$to_look = array_reverse( $children[ $page_id ] );

		while ( $to_look ) {
			$p           = array_pop( $to_look );
			$page_list[] = $p;
			if ( isset( $children[ $p->ID ] ) ) {
				foreach ( array_reverse( $children[ $p->ID ] ) as $child ) {
					// Append to the `$to_look` stack to descend the tree.
					$to_look[] = $child;
				}
			}
		}
	}

	return $page_list;
}


Top ↑

Changelog

Changelog
VersionDescription
1.5.1Introduced.

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