Exclude page children from the WordPress search results

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.

 

 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');
 

One Response to “Exclude page children from the WordPress search results”

Comment on this article...

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>