WordPress Single Category Search

custom-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):

…/wp-admin/categories.php?action=edit&cat_ID=3

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 September 7, 2009 by Alex Mansfield

9 responses to “WordPress Single Category Search”

  1. Dang!
    That’s a great WP ‘hack!’
    I am definitely going to have to use that!

    What code highlighter are you using? It’s nice.

    (fyi, you have a broken link in your footer.)

  2. shawn says:

    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.

  3. WPExplorer says:

    This is really helpful. I was trying to limit my search bar so results from my blog would not show up…works great. thanks!

  4. […] WordPress Single Category Search – Alex Mansfield Single category search WordPress hack. (tags: wordpress) […]

  5. AcoGu says:

    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!

    • alexmansfield says:

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

Leave a Reply

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

  • PublishedSeptember 7, 2009
  • Posted InWordpress