Define categories for WordPress search results

By default, WordPress searches for everything on your site. If a user types a word or the entire phrase in a search box, he will get results from the entire website and that includes posts, pages, categories and tags, titles and content, etc. If you haven’t installed any other commenting system, or already have made changes, you may want to modify the default search box.

We have already showed you how to search only through titles, how to show more posts in search results page and even how to setup the entirely new search box where users can go through specific categories or even select ones by themselves. But if you want to modify the search box which already exists in your WordPress and define categories which will be included in the result pages, you may take a little different approach.

In this article, we’re about to show you how to do that. You can easily add or remove categories from the code and decide which one you (don’t) want in your search results.

Add or remove categories from search results:

  1. Open functions.php
  2. Copy and paste the code.
  3. function searchcategory($query) {
    if ($query->is_search) {
    return $query;
  4. Add categories’ ID on the 3rd line
  5. Save changes

Now that you have made the changes, search results will only get information from specified categories while the other ones will be excluded. As you can see, you can easily add categories on the list; you can have only one category if you want to, or you can set as many as you’d like your visitors to be able to search through. Simply write category IDs separated by commas.

If your only goal is to exclude a category or two from the search results, you can do it much quicker; instead of typing in all the categories you want to include, you can exclude one by typing a minus (-) sign in front of the category ID. For example, if you want to exclude a category which has ID=1, the third line of code would look like this:


There you go. Now you can manage your search results more efficiently.

If you were interested in this, you might want to exclude entire posts or pages collection from your search results.


This guide is an introduction to mastering the art of blogging. It provides easy to follow steps to start, maintain, and grow your blog.

Read the guide

One thought on “Define categories for WordPress search results

  1. Hi Ivan, its important to make sure you block spiders from crawling WordPress archive and category pages as well due to index bloat and duplication.

Leave a Reply

Your email address will not be published. Required fields are marked *