I will really appreciate your help to create a function that will check by a given $my_custom_post_type_name
and $post_name
and return true
if the current page / post is a $post_name
or $post_name_child
or $post_name_grandchild
and so on based on the provided parent slug and custom post type.
Let's say this is the structure:
my_custom_post_type_name
-first_page (example.com/my_custom_post_type_name/first_page)
--first_page_child
---first_page_grandchild
--first_page_child_2
-second_page
--second_page_child
---second_page_grandchild
I want to be able to target all pages that are first_page
or its children / grandchildren and so on.
Something like:
if( my_custom_function('my_custom_post_type_name', 'first_page') ){
//do stuff if the current page is 'first_page' OR 'first_page_child' OR 'first_page_grandchild' OR 'first_page_child_2'
}
After some research I was able to come up with the following (still need to change first_page ID
to be a slug, and to get rid of in_array()
check so the custom function will do it all at once):
function get_posts_children($CPT, $parent_id){
$children = array();
$children[] = $parent_id;
// grab the posts children
$posts = get_posts(
array(
'numberposts' => -1,
'post_status' => 'publish',
'post_type' => $CPT,
'post_parent' => $parent_id
)
);
// now grab the grand children
foreach( $posts as $child ){
// call the same function again for grandchildren
$gchildren = get_posts_children($CPT, $child->ID);
// merge the grand children into the children array
if( ! empty($gchildren) ) {
$children = array_merge($children, $gchildren);
}
}
// merge in the direct descendants we found earlier
$children = array_merge($children, $posts);
return $children;
}
//and then (where 3060 is the first_page ID):
global $post;
if( in_array( $post->ID, get_posts_children( 'my_custom_post_type_name', 3060 ) ) ) {
//do stuff. As it is now, it is working fine. But would really like to simplify it and to change the first_page ID to be a slug for obvious reasons.
}