How to Use Multiple Search Forms In WordPress

Recently we showed you how to limit search results for specific post types in WordPress. Now we are going to show you how you can create different/multiple search forms altogether. This way each form can be limited to searching for a specific post type. Although this isn’t very hard it will require you to have a basic understanding of WordPress templates.

First, you will need some search forms. Place the following code wherever you want them to be in your blog:

1 <form method="get" id="searchform" action="<?php bloginfo('home'); ?>/">
2 <input type="text" value="" name="s" id="s" />
3 <input type="hidden" name="search-type" value="normal" />
4 <input name="submit" type="submit" value="Go" />
5 </form>

In order to specify what sort of search this form will be doing, just change the value of the hidden field. Right now it is set to “normal” but it can be anything you want. Next, we need to modify the search.php file. Open it up and replace everything in it with this code (copy the existing code to your clipboard first, you will need it in a minute):

01 <?php
02 if(isset($_GET['search-type'])) {
03     $type = $_GET['search-type'];
04     if($type == 'random') {
05         load_template(TEMPLATEPATH . '/normal-search.php');
06     } elseif($type == 'books') {
07         load_template(TEMPLATEPATH . '/books-search.php');
08     }
09 }
10 ?>

So we will be assuming that you have two search forms, normal and books. This code is simply redirecting the search to the php file that handles that specific query. Now we just have to create those files. So, go ahead and create a normal-search.php and books-search.php file (just replace “normal” and “books” with whatever values you have been using).

Now, in normal-search.php copy and paste the following code:

1 $args = array( 'post_type' => 'post' );
2 $args = array_merge( $args, $wp_query->query );
3 query_posts( $args );

Immediately after this paste the loop code from your clipboard that you copied from the search.php file. Together, this code will search only your normal blog posts. Now, in the books-search.php file add this bit of code and again paste the loop right after it:

1 $args = array( 'post_type' => 'books' );
2 $args = array_merge( $args, $wp_query->query );
3 query_posts( $args );

This will cause WordPress to search only for the custom post type of “books”. You can repeat this process for as many search forms as you would like.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s