Identifies 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.
Parameters
$page_id
intrequired- Page ID.
$pages
WP_Post[]required- List of page objects from which descendants should be identified.
Source
$found_id = 0;
foreach ( (array) $pages as $page ) {
if ( $page->post_name === $revparts[0] ) {
$count = 0;
$p = $page;
/*
* Loop through the given path parts from right to left,
* ensuring each matches the post ancestry.
*/
while ( 0 !== (int) $p->post_parent && isset( $pages[ $p->post_parent ] ) ) {
++$count;
$parent = $pages[ $p->post_parent ];
if ( ! isset( $revparts[ $count ] ) || $parent->post_name !== $revparts[ $count ] ) {
break;
}
$p = $parent;
}
if ( 0 === (int) $p->post_parent
&& count( $revparts ) === $count + 1
&& $p->post_name === $revparts[ $count ]
) {
$found_id = $page->ID;
if ( $page->post_type === $post_type ) {
break;
}
Changelog
Version | Description |
---|---|
1.5.1 | Introduced. |
Examples
In one of my Hierarchical Custom Post Type (
locations
) I did @bhlarsen’s method, and in some extent it’s returning false children. So I did it my way:It’s giving me the correct children.