Exclude children terms only from a specific post type from parent taxonomy archive

Please find below code which I tested with custom taxonomy called “hobby” which is assigned to default post type “post” and custom post type “student”. You should change the relative field with below code.


add_action( 'pre_get_posts', 'cyb_pre_get_posts' );
function cyb_pre_get_posts( $query ) {

if( $query->is_tax( 'hobby' ) && $query->is_main_query() && !is_admin() ) {

$children = get_term_by( 'slug', $query->query_vars['hobby'], 'hobby' );
if( $children->parent == 0 ) {

/// find child post entries
$posts_array = get_posts(array(
'posts_per_page' => -1,
'post_type' => 'student',
'fields' => 'ids',
'tax_query' => array(
array(
'taxonomy' => 'hobby',
'field' => 'slug',
'terms' => $query->query_vars['hobby'],
'include_children' => false
))));

$posts_post = get_posts(array(
'posts_per_page' => -1,
'post_type' => 'post',
'fields' => 'ids',
'tax_query' => array(
array(
'taxonomy' => 'hobby',
'field' => 'slug',
'terms' => $query->query_vars['hobby'],
'include_children' => true
))));

$query->query_vars['post__in'] = array_merge($posts_array,$posts_post);
}

}
}