How To Create Search By Category Functionality In WordPress

Search by category is a an usual functionality in almost websites that allows you to search in a specific category instead of whole website for more accurate results. It is very useful if your website is well-structured by categories (for example: an e-commerce websites that each category presents one type of products). Unfortunately, this functionality is not implemented in WordPress. In this article, we’ll see how to extend the WordPress’s default search functionality to allow search by category.

Add list of categories to search form

To search by category, we need to implement the search box first. The search box needs to be added one more field – category – which is shown as a select box.

How To Create Search By Category Functionality In WordPress

This is done simply by adding the function wp_dropdown_categories() into the search form. All you need to do is put the following code into searchform.php file of your theme (this is the file where search form code is stored by default, but not always necessary):

<form id="searchform" method="get" action="<?php echo home_url(); ?>">
    <input type="text" name="s" id="s" size="15" />
    <?php wp_dropdown_categories( 'show_option_none=Select' ); ?>
    <input type="submit" value="Search" />
</form>

If your theme doesn’t have the searchform.php file, try to find the code of search form in header.php file (or sidebar.php, it depends on the location of search form in your blog) and then replace it with the code above.

If you want to know more about wp_dropdown_categories() function, you should read the Codex.

After that, refresh your blog, you’ll see the select box of categories is shown as in the screenshot.

Add category to search parameters

Try to search with the new search box. You’ll see nothing is changed, but the url. The old url contains search parameter (which is “s”) only, but the new url contains one more parameter – category (which is “cat”). The new url looks like this:

http://localhost/wp/?s=image&cat=120

Now we need to tell WordPress to understand the category parameter and get proper posts. Add the following code into functions.php file:

add_action( 'pre_get_posts', 'search_by_cat' );

function search_by_cat()
{
    if ( is_search() )
    {
        $cat = empty( $_GET['cat'] ) ? '' : (int) $_GET['cat'];
        add_query_arg( 'cat', $cat );
    }
}

Here we hook into pre_get_posts action. This action is fired when WordPress prepares the query before getting posts from database. Our hooked function do the following actions:

  • check if the current query is search
  • get the category parameter. Note that if user doesn’t choose any category (which means search in all categories) then the category parameter is set to -1. So we need to check this to make sure the category parameter is an positive integer or empty string if no category is chosen
  • add the category parameter to current query parameter array

Now you can refresh your blog and try some searchs. Don’t forget to choose category to narrow the search results. You’ll see the search by category functionality works well as expected.

The search by category functionality is very useful for some types of WordPress blog like a download website or an e-commerce website, which all the content are well-arranged in its category. This feature is helpful for users because they’ll find what they need faster and more accurately. Implementing search by category is a good way to improve user experience in your website.

I hope this tutorial is helpful for you. If you have any question, please leave in the comments.

19 Comments

  1. i want to search category, subcategory and product name, vendor, sku in plug in woocommerce. how i need to do first? please help

  2. Hola es lo que estaba buscando solo que también necesito que busque por mes, alguien me podría ayudar.
    Gracias
    Saludos
    Juamar

  3. Iago Melanias

    July 22, 2013 at 3:01 AM

    Hello,
    Thanks for the code.

    However, your post has some errors. See:
    Line 3, code 1. The < and the ? are separated.
    Line 8, code 2 (functions). The function “add_query_var” is invalid, the correct would be use “add_query_arg”.

    Making these modifications, the code works perfectly today.

    Thank you.

  4. I have doubt.
    I want to show some specified Categories in My sidebar.

    How can I Do That One

  5. hii ,can you tell me ,the code you mention in above that replace or just add in the files searchform.php and function.php

  6. great, thank you ! I use it because I cannot have a result page showing all posts at once due to appearance differences based on post category.
    However, how could we modify the code to exclude “select” and to point directly to a category with no option therefore of getting all category posts at once in the search results ?

  7. Johannes Persson

    April 17, 2013 at 3:38 PM

    Great tutorial! I’m not that proficient with php, and this really helped me understand it.

    However, I was wondering how I would use this if I have a different taxonomy called product_categories. When I try to perform a search with a category I end up with a server error.

    Any help is greatly appriciated, thanks in advance!

    /Johannes Persson, Stilius Web & Design

  8. Very helpful post for novice developer…!!!

  9. Great tip.
    Thanks for sharing.

  10. Hello,

    I don’t know why, but using this tips dosen’t work for me either, like caroline. Adding the two codes is ok, but when searching, if a category is selected, it redirects to the category page. If no category is selected, the search works, but including the classic way with all cats.

    I have search so many websites to find why, but i can’t see any good answers. print_r($wp_query); shows [s] => [sentence]. It’s like the_search_query isn’t saving with a cat selected.

    If you could help. Thanks.

    • rilwis

      September 5, 2012 at 9:03 AM

      Does the search URL “?s=sentence&cat=123” work when you enter it directly to address bar?

      • No, i forgot to tell it, but ?s=X&catY redirects to /cat/y too. I have just installed my wordpress with wordpress seo, and some minor plugins on a new dedicated serveur (debian) Maybe the problem comes somewhere else in the imported db ? I have put off some functions related to cat in functions.php, but that didn’t solve. Now i don’t know where to search.

        • Oh yes, that’s it ! WordPress SEO. There was an option activated to clear the URL. Arf ! Very sorry for that and hope it can help someone else ;) My god, i now looks like – yes you know… :D It works now great. Thanks for you code.

  11. Great! But there’s something wierd! When I use this in my sidebar from searchform.php i write and then choose category. But when I use the code by itself in my header, it’s unable to search and only shows posts from choosen category :(

    Why is that so?!

  12. Awesome, thnx for sharing. My client requested a ‘search by category’ feature and I didn’t want to go the route of adding another plugin, so this is perfect!

    I cannot get the search to work correctly if a category isn’t chosen. It’s working perfectly if a category is chosen but if a category isn’t chosen, the category parameter is set to -1 and no search results appear even though they should.

    I’ve added the pre_get_posts action and function to the functions.php file just as it’s written above. This is hosted locally so I cannot share a url with you.

    Any ideas?

    • rilwis

      August 29, 2011 at 3:03 PM

      In the code, the category parameter is set to empty string if no categories were chosen: $cat = ($cat > 0) ? $cat : '';. You should show the parameters of the current query to see its value (simply hook to wp_head and use print_r($wp_query);)

Leave a Reply

Your email address will not be published.