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:

    <form method="get" id="searchform" action="<?php bloginfo('home'); ?>/">  <input type="text" value="" name="s" id="s" />  <input type="hidden" name="search-type" value="normal" />  <input name="submit" type="submit" value="Go" />  </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):

    <?php  if(isset($_GET['search-type'])) {      $type = $_GET['search-type'];      if($type == 'random') {          load_template(TEMPLATEPATH . '/normal-search.php');      } elseif($type == 'books') {          load_template(TEMPLATEPATH . '/books-search.php');      }  }  ?>  

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:

    $args = array( 'post_type' => 'post' );  $args = array_merge( $args, $wp_query->query );  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:

    $args = array( 'post_type' => 'books' );  $args = array_merge( $args, $wp_query->query );  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.

Seraphinite AcceleratorOptimized by Seraphinite Accelerator
Turns on site high speed to be attractive for people and search engines.