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
1 2 3 | <?php wp_dropdown_categories('show_option_all=All Category'); ?> |
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
1 2 3 | ?s=a&cat=120 |
Step 2: Add category to search parameters
Next, add the following line of code into the functions.php file.
1 2 3 4 5 6 7 8 9 10 11 12 | add_action('pre_get_posts', 'search_by_category'); function search_by_category() { global $wp_query; if (is_search()) { $cat = intval($_GET['cat']); $cat = ($cat > 0) ? $cat : ''; $wp_query->query_vars['cat'] = $cat; } } |
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!