Create multiple search templates for custom post types

Adding these snippets to your wordpress theme will enable you to setup multiple search templates for custom post types.

Search template

Create a new file called search.php and add the following search template. Change the $search_refer= CUSTOM_POST_TYPE to the names of your post types. You will also need to change the template path to the corresponding template you wish to display results.

<?
/* Template Name: Search Results */
$search_refer = $_GET["post_type"];
if ($search_refer == 'CUSTOM_POST_TYPE') { load_template(TEMPLATEPATH . '/template_one-name.php'); }
elseif ($search_refer == 'CUSTOM_POST_TYPE') { load_template(TEMPLATEPATH . '/template_two-name.php'); };
?>

 

Display search results

Add this query_post just above the loop in the search templates that you create. Don’t forget to change the CUSTOM_POST_TYPE for each of your templates.

 

<?php
$args = array(
'post_type'=> 'CUSTOM_POST_TYPE',
's'    => $s);
query_posts($args);
?>

Search form

Add this HTML to the template you wish to display the search form. You will need to change the CUSTOM_POST_TYPE name to the post type you wish to search. You will need to create a new form for each custom post type or use a select menu to set the post_type.

<form id="searchform" action="<?php bloginfo('home'); ?>/" method="get">
<input id="s" maxlength="150" name="s" size="20" type="text" value="" class="txt" />
<input name="post_type" type="hidden" value="CUSTOM_POST_TYPE" />
<input id="searchsubmit" class="btn" type="submit" value="Search" />
</form>

Leave a comment