Recently, we had a client who wanted a special recipe search. There were 2 ways to extend the search functionality – manually or dynamically.
1. Search One or More Categories Manually
If we want to search one category, we could have used this solution which lets you manually add category numbers to the search function:
[Replace value=”5″ with your category number.]
<form method=”get” id=”searchform” action=”<?php bloginfo(‘home’); ?>/”>
<div>
<input type=”text” value=”<?php echo wp_specialchars($s, 1); ?>” name=”s” id=”s” />
<input type=”hidden” name=”cat” value=”5″ />
<input type=”submit” id=”searchsubmit” value=”Search” />
</div>
</form>
2. Search Subcategories Dynamically
However, we wanted to dynamically search only the subcategories of the Recipe Category. The reason being that if you’re already in the Recipes section of the site, seeing a recipe labeled as Recipes is not helpful. However, seeing a recipe labeled as Dessert (mmm..) and Breakfast is helpful. So, each recipe that the client adds will be in a subcategory of recipes (ex. Dessert), but they won’t have to check off the checkbox next to the Recipes category itself.
Anyway, I’ve been looking for this solution for a long time and now, thanks to Ilan Cohen, I present it to you.
[Replace the number 5 with the parent category.]
<form method=”get” id=”searchform” action=”<?php bloginfo(‘home’); ?>/”>
<div id=”search”>
<input type=”text” value=”Search… ” onclick=”this.value=”;” name=”s” id=”s” />
<?php $categories = get_categories(‘child_of=5′);
$catlist = ”;
foreach ($categories as $cat) {
$catlist.= $cat->cat_ID.’,’;
}
$catlist.’5′;
?>
<input type=”hidden” name=”cat” value=”<?php echo “$catlist”?>” />
<input name=”” type=”image” src=”<?php bloginfo(‘stylesheet_directory’); ?>/styles/<?php echo “$style_path”; ?>/search.gif” value=”Go” class=”btn” />
</div><!–/search –>
</form>
The code searches through all the child categories of Category 5 (Recipes). Then, you’ll see we added an additional “5” in this line: $catlist.’5′; just in case the client puts a recipe in the Recipes category, and not one of its subcategories.
Pingback: How to Hack the Wordpress Search Function: Search Categories and … | wpden()
Pingback: How to Customize Multiple Search Result Pages in Wordpress | Wordpress Garage()
Pingback: 10 Useful WordPress Search Code Snippets « UKWDS!()
Pingback: 10 Useful WordPress Search Code Snippets « Referência própria do wordpress()
Pingback: WordPress as a Knowledgebase | Call me stupid, but...()
Pingback: 10 Useful Wordpress Search Code Snippets - Speckyboy Design Magazine()