Search in one category wordpress

How to Search By Category in WordPress (Best Method)

Last updated on September 2nd, 2022 by Editorial Staff | Reader Disclosure Disclosure: Our content is reader-supported. This means if you click on some of our links, then we may earn a commission. See how WPBeginner is funded, why it matters, and how you can support us.

Do you want to add search by category in WordPress?

Adding a category-specific search to your website can help visitors find what they’re looking for. Visitors can search particular blog categories, product categories, membership levels, and more.

In this guide, we’ll show you how you can add a search by category feature to WordPress.

Why Add Search By Category to WordPress?

If you have a lot of content, then categories can help organize that content.

Categories can also help visitors find interesting posts, for example many sites show their categories in a menu or sidebar.

You may want to go one step further and add a search by category feature to your archive pages or other areas of your site.

Overall, category-specific search gives your visitors a better experience on your site, which will help increase pageviews and reduce bounce rate. This sends positive signals to the search engines and can improve your WordPress SEO.

If you’re using WooCommerce, then you can add a product category search.

This can help visitors find more products to buy on your online store.

With that being said, let’s see how you can add a search by category feature to WordPress.

How to Add Search By Category in WordPress

The easiest way to add a category specific search to WordPress is by using SearchWP.

It is the best search plugin for WordPress and gives you complete control over the search experience on your website.

With SearchWP, you can search content that WordPress ignores by default, including custom post types, PDF files, WooCommerce products, and categories.

First, you need to install and activate the SearchWP plugin. For more details, see our step by step guide on how to install a WordPress plugin.

Upon activation, head over to Settings » SearchWP and then click on ‘License.’

You can then enter your license key in the ‘License’ box and click the ‘Activate’ button.

You can find the license key by logging into your SearchWP account.

Once you’ve done that, you’re ready to create a new search engine by clicking on the ‘Engines’ menu option.

This takes you to a screen where you can set the default search engine settings. Think of it like creating your own Google search algorithm that’s just for your WordPress website.

Here, you’ll see a section for the different content types that SearchWP searches by default, such as pages and posts. Each section has an Application Attribute Relevance that will change how the search engine ranks this content on your WordPress blog.

For example, if you move the ‘Title’ slider to the left and the ‘Content’ slider to the right, then the content will carry more weight than the title.

When you’re happy with how the search engine is set up, click on the ‘Save Engines’ button to save your changes.

At this point you may see a message asking you to rebuild the index. If this happens, then just click on the ‘Rebuild Index’ button.

Next, we’re going to customize the search form to add a category selection option, so your visitors can decide which category they want to search.

To do this, you’ll need to add code to your WordPress website.

Often you’ll find code snippets in WordPress tutorials with instructions to add them into your theme’s functions.php file or a site-specific plugin.

However, this isn’t very quick or beginner-friendly. Even worse, a tiny mistake in the custom code snippet can cause common WordPress errors or even break your site completely.

With that in mind, we always recommend you add custom code snippets using the WPCode plugin. WPCode makes it easy to add code snippets in WordPress without having to edit your theme’s functions.php file.

For more details, see our step by step guide on how to add custom code in WordPress.

You can then add the following PHP snippet to your website:

This code adds a category dropdown menu to all of the search forms on your WordPress blog or website.

There are lots of other ways you can use SearchWP to deliver more accurate and relevant search results. For more information, please see our step by step guide on how to improve WordPress search with SearchWP.

We hoped this article helped you add search by category in WordPress. You may also want to see our expert pick of the best WordPress plugins for businesses, and our comparison of the best email marketing services.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.


Как добавить поиск по определенным рубрикам в WordPress?

Недостатки стандартного поиска WordPress мы уже обсуждали в одной из наших статей. Также рассмотрели несколько способов улучшить поисковый механизм. Теперь рассмотрим добавление такой возможности, как поиск по выбранным рубрикам сайта. Согласитесь, что это очень удобно, особенно если Вы находитесь на каком-то новостном портале, включающем большое количество тематик. Исключение ненужной информации из поиска позволит быстрее посетителю сайта найти нужную ему информацию. Кроме того, это уменьшит нагрузку на сайт в целом.

Как выбрать категорию для поиска?

Форму поиска по категориям будем выводить в виджете на боковой панели. С этой задачей хорошо справляется бесплатный плагин Category Wise Search . Так, после его установки и активации, необходимо перейти на страницу виджетов (Внешний вид -> Виджеты). Как видим, плагин добавил свой виджет под названием Category Wise Search.

Далее необходимо виджет перетянуть в нужное место сайдбара (обычно поиск выносят на самый верх), после чего откроются его настройки. Рассмотрим подробнее самые основные из них.

В текстовом поле Default select box text Вы можете указать текст, который будет отображаться в блоке выбора категории на сайте.

Если нужно исключить какие-либо категории из поиска, можно прописать их ID в поле Exclude Categories.

Настройка Default select category позволит указать, какая категория будет отображаться в форме поиска (по умолчанию стоит значение, заданное в поле Default select box text).

После внесения всех изменений необходимо нажать кнопку Сохранить.

Нажмите, пожалуйста, на одну из кнопок, чтобы узнать понравилась статья или нет.


Improve the Search Function of Your WordPress Website

Once you start writing blog content and accumulate more than just a few articles, you will hopefully get more visitors to your site. And when they get there, your visitors will want only the best content and that’s only true if they are interested in the topic. So, even if you narrow the field and write only about, let’s say PC games and not all video games, people will still not be interested in every article you have written so far.

Читайте также:  Linux что является интерпретатором

Besides links and recommendations by you or other visitors, you will want to give your users the power of searching through your site.

The same way people search on Google to get to your site, you want them to be able to search through your blog as well. Yes, there is a default search feature already integrated into WordPress. But if you have tried working with it, you have probably noticed it is not as good as you imagined, even though it has improved over the years.

So, in order to make the search feature even better, you can do a few things I am about to show you in this article.

Best search plugins for WordPress

With the variety of WordPress plugins, you shouldn’t worry about modifying the search function. There are numerous great plugins that will extend your search possibilities and you will proudly present your search box on the site you own.

If you do everything right, users will likely type what they want in your new search box and get the results they expected. Now let’s see some of the best WordPress search plugins you can install in a matter of minutes.


Let’s start with a plugin that will help you get the power of the Google search engine on your website. This free plugin will help you set up a Google search box which you can easily place on your website as a widget.

You will have to register a Google Custom search account, get the ID and the plugin will do the rest. Then, your visitors will be able to search your site or the entire web, depending on your settings, or even search only for images if you decide to do so. You can customize many search features, apply custom layouts, change colors, fonts, thumbnails, and much more.

  • Results powered by Google
  • Direct link to Google Analytics
  • Autocomplete


This modern plugin is already used by many popular websites which recognized its power. Not only Swiftype features one of the best search algorithms which will give you meaningful results, but it gives you a detailed insight into all searches made on your site. With this feature, you can easily find the best keywords for your website and make the content and your search results even better.

The plugin will replace standard WordPress search, and once you have created a free account you can customize Swiftype to make it as best as it can be for your site. If you have a mobile application that displays content from your blog, you can help your mobile visitors search the content even easier with the mobile SDK.

  • Drag and drop interface
  • Autocomplete
  • Detailed analytics


SearchWP is another popular WordPress plugin which will be a great substitute for the default WP search. After the installation, you won’t have to deal with a difficult setup, but instead, you can configure it to work with custom fields and post types, different taxonomies, etc.

The plugin works great with different media types so it will easily find videos, PDF documents, audio, and much more. Its algorithms take relevance of keywords in your articles so, for example, a word which is found in the title will have more impact on search result than one found in the article, comment, or the sidebar. Developers will like the possibilities of extending the plugin’s functionalities, while you can also install different extensions.

You can expect detailed statistics of search results so you can work on content people are searching for. Currently, there are three different licenses you can choose from, starting from $49 per year.

  • Keyword weight control
  • Search media like video, audio, and PDF
  • Detailed analytics


Relevanssi may sound like something relevant. Actually, it is, because Relevanssi is a Finnish word for relevant. This plugin will replace your default WordPress search engine and make it quite better. To continue the story about the plugin’s name, Relevanssi will sort your results according to its relevance, not the date. And that’s just the first feature on the long list. This powerful plugin can match partial words (fuzzy matching), it will allow you to search for phrases or let you search for just one term.

Create custom excerpts, highlight the results in documents, and do much, much more with this awesome plugin. Relevanssi can search through comments, tags, and custom post types. It will also give you the power to select the weight for titles, tags, and comments and thus improve searching.

One of the numerous features we would like to accentuate is the suggestion function which will give users similar search queries – something like Google’s well-known “Did you mean?” suggestion. Relevanssi offers much more, and this is only a free version that we’re talking about. If you need more, especially if you’re running a multisite, you should take a look at a premium version.

  • Fuzzy matching
  • Highlighted search terms in documents
  • Suggestion based search results


SearchIQ is another great WordPress search plugin that provides an enhanced search experience to users. With powerful search logic, advanced semantic analysis, error handling, and many such features, SearchIQ directs users to the results they were looking for. SearchIQ is quite easy to install and customize.

Getting started requires creating an account on SearchIQ, install and activate the plugin, copy the API key from the SearchIQ dashboard, and enter the API key in the WP backend. The free version is available with basic features and for businesses in need of advanced features such as PDF, CDN, Facet, or custom branding, paid packages can be subscribed to.

Not only you can search across pages, posts, WordPress default system fields, user-defined custom fields, product attributes and taxonomies, PDFs, and excerpts. But SearchIQ’s dashboard also includes real-time analytics data that helps you to understand your user’s search behavior so you can optimize your content strategy better.

Search Everything


Another great free substitute for your default WP search is definitely the Search Everything plugin. It will improve your search results without modifying templates. You can set it up to search almost everything in your WordPress including pages, excerpts, drafts, attachments, comments, tags, and even custom fields. Besides that, you are free to leave out pages and post you don’t want to be found in the search results.

This plugin comes with a little helper named Research Everything which will search for your content while you write a new article and will give you the ability to link to other content immediately. If you want to research, even more, Power Search feature will help you find content on the Internet. If you’re in the run, simply install and activate the plugin without even looking at the settings page and you’ll have an improved search engine up and running in a matter of minutes.

  • Exclude content you don’t want to be searched
  • Research Everything and Power Search included
  • Does not modify your template pages

Change default search URL slug in WordPress

Unless your website is a one-page website which only contains the name of your company and contact info, if you ask us, a search feature is a must-have feature. It doesn’t matter if you are just starting a blog or already have thousands of posts and pages on your website, whether you write as a hobby or make money from your blog, you have to do everything to keep your visitors on the site. Giving them an easy and quick way of searching through your website is definitely one of the crucial things you should take care of.

Читайте также:  Как заправить картридж 226х

It doesn’t matter if you use WordPress’ built-in search engine or if you have installed a different one, you need to take care of search results.

While there are many things you can do about your search feature, you may have forgotten about one simple yet important thing. Yes, we’re talking about that URL slug that appears in the address bar once the search returned the result page.

By default, WordPress uses a non-user-friendly version of the slug. Not only your visitor will find that slug weird, but it may harm your SEO as well. Better to say, you can help your SEO by changing the slug into something understandable both to humans and machines.

If you have tried searching through your website, you could have seen that strange /?s=term slug which appears in the address bar. In this part, we’re about to show you how to change that into anything you want. For example, we’re about to change “/?s=term” into “/search/term” which will be easier to remember and use.

  1. Open functions.php
  2. Copy and paste the following:
  1. Change destination URL on the third line to whatever you like
  2. Save changes

After you’ve done these changes to your functions.php file, you can try out your new URL slug. Don’t worry; if a plugin or a user tried to get access to your search result by navigating to old URL slug, your website won’t return an error but simply redirect the search result to the new URL.

If you want to change the slug to something unique, you can do that on the third line of the code.

This one will take your search results page to –

Now you can relax and stop thinking about how search results are displayed to your users as well as to search engine bots who will now more easily crawl through those results. Also, isn’t it somehow more natural to see the whole “search” word instead of that weird question mark followed by the letter “s”? Tell us what you think.

Search posts exclusively by their titles

If you’re still using the default WordPress search engine, sooner or later you will want to modify how it works. While there’s nothing wrong with the way it searches for your posts, you might want to limit the search to titles.

Instead of going through all of the content, this little function will search only through post titles. In some cases, this might really help you get cleaner and faster search results:

  1. Open functions.php
  2. Copy and paste this code:

After the changes, you can open your website and start a new search. To be sure everything’s working as it should, you should try searching for a word you know is in one of your post titles which should return the post on the results page. If you try to search for a word or a complete term that isn’t contained in any title which you have published, search results will come out empty.

And that’s actually all there is. If you ever decide you want the old search back, simply erase or comment out the function.

Improve the search function and find results within a category

The default search function in WordPress is getting better and better with every update. You can easily include a search feature on your blog and allow people to easily find the content they want. But if you haven’t made any changes to the function, search results will display everything related to the query. And that might be a problem if you have a lot of content because people will have tons of text on the results pages which won’t help them a lot.

In this part of the article, we will show you how to allow your visitors to search only within specific categories which you can define in the code or allow visitors to select ones from the drop-down list.

Select categories in advance:

First, we will show you the code which will create a new search box. With this code, you won’t let people select categories for their search but you will define categories within the code. This might help you with special categories which need a separate search box.

For example, you may have a category that contains only smartphone reviews in it. With this code, you can allow people to search only through that category so that the search results don’t load information about home appliances or other stuff you have on the website. Makes sense, right?

  1. Open a page where you want the search box to appear or make a new widget from it
  2. Copy and paste the following code:
  1. Change the value on the third input type to category ID which you want to search
  2. Save changes

After you have made these changes, a new search box will appear and it will allow you to search through the category which ID you have entered in the code above. If you want to search through multiple categories, simply add more IDs by entering numbers separated by commas.

While this might be a great solution in some cases, there will be times when you will want to show a list of categories and allow visitors to choose where to search from.

Following the same example where you have categories like smartphones, desktop computers, laptops, home appliances, etc. why wouldn’t you allow a visitor to choose one of those and search only through the “laptops” category, for example?

In the following lines, we will show you how to do that:

  1. Open sidebar.php or wherever you want the search box to appear
  2. Copy and paste the code:
  1. Change categories under option values. Write category slug in value and a name between tags
  2. Save changes

Automatically show all categories on the list:

If you want to show all categories and you don’t want to worry about adding or removing ones from this code once you add/delete them in your admin panel, use this code between tags:

This code will generate a list of all available categories.

And that’s it. Now you can easily add one or more categories which your visitors can easily search through. Whether you want people to select the category themselves or you want to specify those in the code, you are covered.

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 search system, or already have made changes, you may want to modify the default search box.

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 part, 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.

Читайте также:  Adding permanent route linux

Add or remove categories from search results:

  1. Open functions.php
  2. Copy and paste the code.
  1. Add categories’ ID on the 3 rd line
  2. 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 the third line of code would look like this:

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

Exclude pages or posts from your WordPress search

In most cases, you will want your visitors to be able to search through your posts while results coming from pages might only distract a typical “searcher”. If your pages contain contact information, maps, author info, etc. you probably don’t need those pages to be included in the search results.

While there is no easy way of telling WordPress to exclude a post type from search results, you will need to do that by yourself:

  1. Open functions.php
  2. Copy and paste the following code into the file:

After you have made the changes and save them, you are free to visit your website and test the search engine. If everything’s ok, you shouldn’t be able to find any information from your pages in the search results, i.e., you successfully exclude pages from WordPress search results.

In the introduction, we told you that WordPress goes through posts and pages and assumed you don’t want pages to show in the results. But what if you don’t want posts to be included in those results? If so, you can make one simple change to the code and exclude posts instead of pages:

Again, you will need to repeat those 3 simple steps shown above, but with a simple change in line #3. Instead of setting post type to “page”, you have to set it up to “posts”:

Don’t forget to save everything and you’re done.

Exclude pages/posts from search results with a plugin

Instead of working with the code, we will show you a plugin that can do the same job for you and make everything much more user-friendly.

Search Exclude


The plugin we have used for the job is Search Exclude. Using the plugin couldn’t be easier:

  1. Navigate to Plugins->Add New
  2. Search for “Search Exclude”
  3. Install and activate the plugin
  4. Go to any of your posts and pages
  5. On the right side panel, find a “Search Exclude” checkbox where you can decide whether you want the post/page to be excluded from your search results or not.

Once you have excluded several posts/pages, you can easily find the list of excluded items in the plugin settings (Settings->Search Exclude). On the list, you can again use the checkbox to change the status of a post/page.

How to exclude only some pages/posts from your search results

It doesn’t matter if it’s only one page, two or ten which you want to exclude from showing in the search results, you can do that easily by implementing the code. Before you rush copy-pasting the code into your functions.php file, we suggest you prepare the pages which you don’t want to be featured in the search results. You will need page IDs:

  1. Go to Pages->All Pages
  2. Find the page you want to exclude and click “Edit”
  3. In the address bar, locate the “post=6” or something similar where the number will represent a page ID

After you have prepared pages’ ID numbers, you are ready for the code:

  1. Go to function.php file and open it
  2. Copy and paste the following code:
  1. On line #3, change the numbers in the brackets to ID numbers that you have read from the page. In this example, we have excluded 6 pages with their respective IDs 1 to 6.
  2. Save changes and you’re done

After you have installed the code, you are free to edit it as needed. If you need to include one of the pages sometimes in the future, simply delete its ID number from the code. The same goes for adding more pages to the “excluded basket”. If you, for example, create a new page which you don’t want to show in the search results, feel free to add its ID number to the code.

Allow usage of Voice Search in WordPress

After smartphones became an important part of our lives, voice search has been improving rapidly. Although never perfect, searching for something on your smartphone has made things like calling a person a much easier task. Yeah, you still have to be very careful with the pronunciation because you might end up calling someone you don’t want to or your speech to text could end up in something not even close to what you have just spoken. Also, asking Siri silly questions is always fun, right?

It doesn’t matter if you like it or not, many people are using the voice search functionality on their phones. So why wouldn’t you allow your visitors to search through your website the same way?

Maybe you didn’t know you can do that with WordPress or you didn’t know how to do it, but now you won’t have an excuse.

Instead of the code, here’s a plugin that will extend your WordPress search.


Before you download and install the plugin, it is important to know that it will work only with Chrome and Safari. If you’re OK with the fact that the plugin won’t work in any other browser, it will give your visitors the ability to search the content using their own voice.

By installing the plugin, you’re not overriding the text input – if a user wants to use the search box in a standard way by typing into it, you should know that functionality is intact.

Also, the plugin should work with any other search plugin you might have installed so you’re free to try it with plugins like Relevanssi or Search Everything.

  1. Go to Plugins->Add New
  2. Search for “Voice Search”
  3. Install and activate the plugin

That’s it. After activating the plugin, you should be able to use voice search without problems. How do you like this feature?

Wrapping up

Unless you have a simple brochure website or anything similar to that, you just have to have a functional search feature embedded to your WordPress website. If it’s a blog that gets updated on a regular basis, there are no excuses.

In this guide, we have shown you how to modify the default WordPress search feature. If you don’t like it, there are several plugins that can substitute the standard search feature in a matter of minutes. No matter what your choice is, make your WordPress site better by improving the search feature.


Поделиться с друзьями