The WordPress search results, by default, contain information from all available posts, pages, and custom post types. In some cases you might feel that you need to exclude certain items from the search results, because you feel that they contain irrelevant or confusing information. Today we’ll take a look at how we can achieve this.
Removing individual items
We’ll start with a way to remove individual posts, pages etc. Edit your theme’s functions.php file and paste this at the bottom.
Modify the array bit in the highlighted line, and replace the numbers with the ids of the posts, pages, or custom post types you want to exclude from the search results page.
The function above will make sure that you are executing a search in the main query outside the administration pages. It will then pass the array of ids you have entered to the post__not_in parameter of the WP_Query so they won’t be retrieved. That’s pretty much it.
If you need help finding the id of a certain item, please take a look at this article.
Removing entire post types
What if you want to exclude entire post types from the search results? No problem, paste in this code instead.
In short what we do here is, first we get all the searchable post types in line 4, then in line 5 we fill in the slug of the post type we want to exclude from our search results. Finally in line 7 we remove it from the array of searchable post types and we instruct WordPress to search in the post types remaining in the array.