Sometimes a seemingly difficult problem requires a simple solution.

I’m currently working on a WordPress-driven site for a client. The client wants a customized blog section that has a different header than the rest of the site to separate it from the main site. One of the requirements for this blog section is that the search bar in the header only searches within the blog.

Researching how to customize WordPress search to have a secondary blog-only search didn’t yield many relevant results. I was able to find a Rob Barrett’s blog post from 2009 that suggested a hidden field in the search form. I tried it with a second search form template and created a simple if/else to show the second search form only on blog-related pages:

<?php if(is_home() || is_single()) { include (TEMPLATEPATH . '/blogsearchform.php');}
else { include (TEMPLATEPATH . '/searchform.php'); } ?>

Everything was good until I tested the blog’s search bar. No results were found, even though the regular site’s search (also done through WordPress) displays results from the blog. With the hidden field in the blog search bar, the resulting url was something like this:

http://www.testsite.com?s=searchterm&site_section=blog

I had modified Rob’s code that filters the search results as so:

<?php $search_refer = $_GET["site_section"];	
if($search_refer == "blog") { $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts("s=$s&post_type=post");
	} ?>

Noticing the similarity between the above URL and the query_posts line, I decided to change the hidden field in the blog search form. Instead of having the site_section hidden field, I changed it to look like this:

<form action="/" method="get"><label for="search">Search in <?php echo home_url( '/' ); ?></label>
 <input id="searchInput" type="text" name="s" value="<?php the_search_query(); ?>" />
 <input type="hidden" name="post_type" value="post" />
 <input id="searchButton" type="submit" value="" /></form>

It worked! The hidden post_type field automatically filters the search to only use posts, thus it only searches the blog. We no longer need any other code to filter the search, as it’s all done within the secondary search form.