WordPress Code Snippets

A fresh mix of code snippets and tutorials

Advanced search for custom post types

33

Setting up custom search forms for custom post types can be tricky business. Here’s a quick & easy guide to make it happen in two steps.

Step 1: Edit the search form

In your WordPress theme, locate the template code used to create your regular search form. Add to it the following hidden input fields:

<input type="hidden" name="post_type[]" value="post" />
<input type="hidden" name="post_type[]" value="page" />
<input type="hidden" name="post_type[]" value="books" />
<input type="hidden" name="post_type[]" value="video" />

Step 2:

Next we want to display the search form that will allow users to search based on custom post type. Add the following code wherever it makes sense in your theme template file(s). For example, search.php or sidebar.php. Here is the custom codes to use:

<form role="search" method="get" id="searchform" action="<?php echo home_url( '/' ); ?>">
	<input type="text" name="s" id="s" <?php if(is_search()) { ?>value="<?php the_search_query(); ?>" <?php } else { ?>value="Search the site" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"<?php } ?> /><br />
 
	<?php $query_types = get_query_var('post_type'); ?>

	<input type="checkbox" name="post_type[]" value="posts" <?php if (in_array('post', $query_types)) { echo 'checked="checked"'; } ?> /><label>Posts</label>
	<input type="checkbox" name="post_type[]" value="pages" <?php if (in_array('page', $query_types)) { echo 'checked="checked"'; } ?> /><label>Pages</label>
	<input type="checkbox" name="post_type[]" value="books" <?php if (in_array('books', $query_types)) { echo 'checked="checked"'; } ?> /><label>Books</label>
	<input type="checkbox" name="post_type[]" value="video" <?php if (in_array('video', $query_types)) { echo 'checked="checked"'; } ?> /><label>Video</label>
 
	<input type="submit" id="searchsubmit" value="Search" />
</form>

And that’s all folks. Once implemented, this technique will enable users to search your site based on custom post type. The search form will display checkboxes for each custom type.

Learn more

WordPress Themes In Depth


Show Support

Like our new Facebook Page to show support!