Add Search by Category Functionality to Your WordPress Site
If you have a site with a lot of content and a number of different categories, then there’s a good chance your visitors will want to search within certain categories and not others. The solution to this problem is to make your site searchable by individual categories.
Below is a way to manually do it.
Manually Expand the Functionality of Your Current Search Box
Another slightly more complicated method is to give your current search box “search by category” functionality. I found this trick at Deluxe Blog Tips.
Place the following code into the searchform.php file of your theme. (Appearance > Editor > Search Form – searchform.php) If your theme does not have a searchform.php file, you can create one:
<form id=»searchform» method=»get» action=»<?php bloginfo(‘url’); ?>»>
<input type=»text» name=»s» id=»s» size=»15″ />
<?php wp_dropdown_categories(‘show_option_none=Select category’); ?>
<input type=»submit» value=»Search» />
</form>
Then put this code at the bottom of your functions.php file. (Appearance > Editor > Theme Functions – functions.php):
add_action(‘pre_get_posts’, ‘search_by_cat’);
function search_by_cat()
{
global $wp_query;
if (is_search()) {
$cat = intval($_GET[‘cat’]);
$cat = ($cat > 0) ? $cat : »;
$wp_query->query_vars[‘cat’] = $cat;
}
}
And here’s the result:
One nice feature of this method is that when you are on the category page for a specific category, the search box will automatically switch to that category for more searches.