Want to exclude a page’s children from displaying in the search results? This example will exclude any child pages of 125 but only if the user is not logged in.
Exclude page children from the WordPress search results
function SearchFilter($query) {
if ($query->is_search) {
if ( !is_user_logged_in() ) {
// exclude children of page 125
$parent = 125;
$children_data = get_pages( array(
'child_of' => $parent,
'post_type' => 'page'
) );
$excludes = array($parent);
foreach( $children_data as $child ) {
array_push($excludes, $child->ID);
}
$query->set('post__not_in', $excludes);
}
}
return $query;
}
add_filter('pre_get_posts','SearchFilter');