WordPress Single Category Search


Sometimes it comes in handy to make the search form on a blog only return results from a single category. It’s actually quite simple.

1. Find the category ID

First we need to find the ID of the category that we want to search. We can find that by going to Posts>Categories and hovering over the category we want to search in the categories list on the right side of the page. When we hover the mouse over a category, we’ll see something like this in the status bar (usually the bottom left corner of the browser):


As you can probably see, the 3 at the end is the category ID. That number is all we need to know.

2. Edit the searchform.php file

We just need to find this line in the searchform.php file of the theme:

<form method="get" id="searchForm" action="<?php bloginfo('home'); ?>/">

and add this hidden field immediately after it:

<input type="hidden" name="cat" id="cat" value="3"/>

3. Apply the category ID

Now we need to make sure that we change the value of the hidden field to the category ID we found in step one. For example, if the category we chose had an ID of 12, then the hidden field would look like this:

<input type="hidden" name="cat" id="cat" value="12"/>

It’s that easy! If you have any questions, feel free to post them in the comments section below.

Image by rockmixer

Posted in

9 thoughts on “WordPress Single Category Search”

  1. How would I go about doing this dynamically?

    Meaning a person is viewing either a category archive page, or a single article and wants to search for other articles within the category page they are viewing.

    So I could have a search box on the sidebar, where if a person is viewing cat ‘abc’ it would search cat ‘abc’ and if a person is viewing an article or archive for cat ‘xyz’ they would get to search ‘xyz’..

    Basically dumping the hardcode and replacing with a dynamic variable determined via the cat displayed.

    1. Interesting idea. I haven’t actually tried this, but here’s how I think I would go about it. First, I would grab the category with the get_the_category() function (http://codex.wordpress.org/Function_Reference/get_the_category). This returns an array of the categories belonging to that post. Then I would extract the first category of the array and use that instead of the hard coded category. I’m not really sure if I explained that very well or not. Let me know how it goes.

  2. Pingback: The Blog of Hanas › links for 2010-12-20

  3. Hi there, very useful code! Thanks.
    I just wanna know how to set this up to let the user to find posts from 2-3 different categories.
    Thanks again!

    1. You can search multiple categories by listing the category IDs separated by commas. For example: value=”3,5,14″

Leave a Comment

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