Created
January 18, 2022 21:59
-
-
Save petenelson/9a2831ed33ce786db5a081da9902c19a to your computer and use it in GitHub Desktop.
WordPress: Get All Descendants
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Gets all of the descendant/child post IDs for a parent post ID. | |
* | |
* @param int $parent_post_id The parent post ID. | |
* @return array | |
*/ | |
function get_all_descendants( $parent_post_id ) { | |
$post = get_post( $parent_post_id ); | |
if ( ! is_a( $post, '\WP_Post' ) ) { | |
return false; | |
} | |
$child_post_ids = []; | |
// Get children for this parent. | |
$children = get_children( | |
[ | |
'post_parent' => $parent_post_id, | |
'post_type' => get_post_type( $parent_post_id ), | |
] | |
); | |
foreach ( $children as $child_post ) { | |
$child_post_ids[] = $child_post->ID; | |
// Recurse back into this. | |
$child_ids = get_all_descendants( $child_post->ID ); | |
if ( ! empty( $child_ids ) ) { | |
$child_post_ids = array_merge( $child_post_ids, $child_ids ); | |
} | |
} | |
return $child_post_ids; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment