How To Exclude Posts From WordPress Search

Keywords

There may be times when you have a little rant of make a mistake in a post and want to exclude this from the in-built WordPress search functionality.

There is a way you can intercept the WordPress search functionality and exclude certain posts from being displayed. All you have to do is find out the post ID and add it to the following function in your functions.php file.

First you need to check is you are currently on the search page by checking if the is_search parameter is set to true. If you are currently on the search page this will be set to true and you can continue to exclude certain post Id's from the page.

You should also check to see if WordPress is currently processing the main query by calling the method is_main_query(). The is main query method will process any queries made to the pre_get_posts hook.

Once these are checked then you know that the query being ran will be the search query from WordPress.

function exclude_posts($query) {
    if ($query->is_search && $query->is_main_query()) {
        $query->set('cat','110, 201, 254, 302');    //Change the numbers to your post IDs
    }
    return $query;
}

add_filter('pre_get_posts','exclude_posts');

Advertise here

Comment