Prevent WordPress search from search a specific pages parentpages

I have a certain page in WordPress that have parent pages. I want to exclude those parent pages from WordPress search.

In functions.php I have tried this:

Read More
function SearchFilter($query) {
if ($query->is_search) {
$query->set('post_parent', '4');
}
return $query;
}

add_filter('pre_get_posts','SearchFilter');

Well with this code only the post_parent is searchable, but I want the opposite. How would this look like?

UPDATE: Problem solved. Here’s the solution (4 is the ID of the specific page where parent pages is to be excluded from search):

function SearchFilter($query) {
    if ($query->is_search) {
        $query->set('post_parent__not_in', array(4));
    }
    return $query;
}

add_filter('pre_get_posts','SearchFilter');

Kind regards
Johan

Related posts

Leave a Reply

2 comments

  1. Use This code function in your Theme’s function.php file with page id which is you want to exclude from your Theme’s custom search bar…And Enjoy with it…!

    // Exclude specific posts/pages from search
    function exclude_pages_from_search($query) {    
    
       if ( $query->is_main_query() && is_search() ) { 
    
             $exclude_ids = array(11);// Array of the ID's to exclude   
             $query->set( 'post__not_in', $exclude_ids );   
            }   
               return $query; 
         } 
    
    add_filter('pre_get_posts','exclude_pages_from_search' );