Build an easy category search in WordPress
I’ve had many projects in the past where clients have asked for a custom search field that allows the user to search for posts in a specific category instead of the entire site. It’s a very simple function to achieve, it requires no PHP, just straight HTML.
Recently I had to revisit this piece of code for a project I am working on and thought I’d share since it’s pretty useful and simple.
We use the standard WP search form code to start
<form method="get" id="searchform" action="<?php bloginfo('url'); ?>/">
<label for="s"><?php _e('Search for:'); ?></label>
<input type="text" value="<?php the_search_query(); ?>" name="s" id="s" />
<input type="submit" id="searchsubmit" value="Search" />
</form>
We add this line of code
<input type="hidden" name="cat" value="1" />
This hidden field is what allows us to search a specific category. This string will be added to the search parameter. For example; the normal search would be something like http://wwwdropthedigibomb.com/?s=(what ever keyword was used), with the hidden field we get http://wwwdropthedigibomb.com/?s=(what ever keyword was used)&cat=1. The value attribute refers to the ID number of your category. This is the only thing you will need to change.
Here is the final code
<form method="get" id="searchform" action="<?php bloginfo('url'); ?>/">
<label for="s"><?php _e('Search for:'); ?></label>
<input type="text" value="<?php the_search_query(); ?>" name="s" id="s" />
<input type="submit" id="searchsubmit" value="Search" />
<input type="hidden" name="cat" value="1" />
</form>
Enjoy!

Pingback: uberVU - social comments