Add Search by Category Functionality to Your WordPress Site

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 are two possible ways you could do that – one with a plugin and another more manually.

Use Search By Category Plugin


This plugin is pretty straight-forward in terms of what it does: it adds a drop-down box to your search function for individual categories. Here’s a look at  it in action.

And a look at the settings page …



After installing and activating this plugin, you will either need to place the following code in your theme where you would like the search box to show up …

<?php if(function_exists('sbc')){
} else { ?>
    // Your regular form code goes here
<?php } ?>

Or you can place the following shortcode in a post or a page.


This info can also be found on the plugin’s instructions page.

Although this plugin doesn’t come with a widget, you can place your shortcode in a text widget, and then if necessary, add the following line of code to the bottom of your functions.php file in order to allow your text widgets to accept shortcodes.

add_filter( 'widget_text', 'do_shortcode');


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" />

Then put this code into 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.


Photo: Pretty woman looking through binoculars against blue background from BigStock