Back to Top

How to add Search By Category In WordPress

How to add Search By Category In WordPress

In WordPress development process, you might need to use a variety of WordPress function and write a custom code for some customization, Today I am going to share a very simple and practical functionality “Search By Category”.

Before few days I was working in one WordPress site which require a search by category functionality. Search by category functionality is for the site as per theme so I thought is not a good idea to use a plugin for such functionality, to write code in the theme is worth more. it is better that it is integrated into the theme because more number of plugin in WordPress, will affect the speed of site and slow down.

Search by category is common and useful functionality in almost all websites which provide to search in a specific category for more accurate results when performing a search.

“Search by category” is not provided by default in WordPress so , In this post, I will explain how you can implement the WordPress default search functionality to search by category function.

Step 1:Add list of categories into a search form

First of all, you need to add the list of categories into a search form which is possible by adding the search box for category and it is very simple.

Open the searchform.php file from your theme and add function wp_dropdown_categories() into the search form

After adding above line of code, check your site ,you will get the dropdown of categories and try to search with the new search box. You’ll get the same result but the URL get changed

Step 2: Add category to search parameters

Next, add the following line of code into the functions.php file.

You’ll get the result search by category functionality works now.Here I hook search_by_category into pre_get_posts action. This action is fired when WordPress prepares the query before getting posts from the database. I strongly recommend that you use pre_get_posts here.

Read: To Remove Non Valid REL Tag from Category url in wordpress

That’s it. Now you are ready with search by category functionality in your WordPress site.The method is very simple but first have to at least be familiar with WordPress.

Do you have a question on applying this code for your own use case in WordPress? Comment below and I’ll answer any questions you have!

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Most Popular Posts

Learn about Variables in LESS CSS

Posted on 4 years ago


How to access Remote File using PHP

Posted on 6 years ago


How to connect to MySQL database using PHP

Posted on 6 years ago