Want to exclude a page’s children from displaying in the search results? Heres how:
This example will exclude any child pages of 125 but only if the user is not logged in.
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');