Skip to content

Instantly share code, notes, and snippets.

@petenelson
Created January 18, 2022 21:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petenelson/9a2831ed33ce786db5a081da9902c19a to your computer and use it in GitHub Desktop.
Save petenelson/9a2831ed33ce786db5a081da9902c19a to your computer and use it in GitHub Desktop.
WordPress: Get All Descendants
<?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