wordpress snippets last updated   : April 22, 2014
we now have 631 snippets

Create multiple search templates for custom post types

wordpress snippet

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.

snippet :  PHP - SEARCH TEMPLATEcopy
<?
/* 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.

snippet :  PHPcopy
<?php
	$args = array(
		'post_type'=> 'CUSTOM_POST_TYPE',
                's'    => $s,
                'paged' => $paged,
                );
		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.

snippet :  HTMLcopy
<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>

  • Lin D.

    This didn’t work on mine

    • http://wpsnipp.com Kevin Chard

      Hi Lin D. this does work I have it running with a number of clients. If you wanted to email me with this form bellow I can help you further via email to get things running and even take a look at your templates if you would like.

      http://wpsnipp.com/contact/

  • Anonymous

    This does work (brilliantly! thank you Kevin) only problem is there is a misplaced } in the
    Display search results section. This might be the source of Lin D’s problem.

    • http://wpsnipp.com Kevin Chard

      @toomanyairmiles:disqus  glad to hear that you like the snippet and thanks for the heads up for that extra } I updated the snippet.

  • http://www.facebook.com/flavioleonardvargas Flávio Leonard Vargas

    Working Great! Thanks a bunch!

  • http://www.cliffpaulick.com Cliff Paulick

    Ooh, great! What about form fields based on taxonomies or custom fields, like for a real estate search field? Just reading the snippet, it looks like a regular free-form search box that searches the post type of the post you’re currently viewing. What if it’s a search box on the homepage or another non-CPT? It doesn’t look like there’s a fallback to a regular ‘ol WordPress search. Please correct if wrong.

    • Caswell

      No no my friend, you seem a little confused
       Check this line:

      You could change it to a custom post selector:

      Business
      News LABEL

      and so on..

      Note that:
        name=”post_type” —-> $_GET["post_type"]; —> = $search_refer.meaning the search is not based on the post type of the post you’re currently viewing.its based on : name=”post_type” value.

  • http://www.facebook.com/vadim.roundhouse Vadim Goncharov

    How do you set up something where “nothing found” messages appears if there is no records in the db? 

  • Tom

    I have a problem with pagination, when custom post type search result is more than 5.

    Any advices?

    • philhoyt

      I tried this on the arg array

      ‘bio’,
      ‘posts_per_page’ => 10,
      ‘paged’ => $paged,
      );
      query_posts($args);
      ?>

  • Caswell

     function custom_search_template() {

    $search_refer = $_GET["post_type"];

    load_template(TEMPLATEPATH . ‘/search/search-’ .$search_refer. ‘.php’);

    }

  • Caswell

    alright, this is what i did for a fall-back:

    1. i created a folder within my template files called “search”. –> TEMPLATEPATH .’/search/’

    2. then created custom post templates using WordPress default search.php code.
    eg. : search-xxxxx.php where xxxxx is the custom post type.

    3. place all search-xxxxx.php custom post templates in the newly created search folder.

    4. rename default WordPress search.php to –> default-search.php

    5. create a new search.php and put the following code:

     

    6. wer’re basically calling a function called custom_search_template().

    7. lets define that function in the file fuctions.php :

    function custom_search_template() {

    $search_refer = $_GET["post_type"];

    if ( isset($_GET["post_type"]))
    {
        if (file_exists(TEMPLATEPATH . ‘/search/search-’ .$search_refer. ‘.php’))
       
        load_template(TEMPLATEPATH . ‘/search/search-’ .$search_refer. ‘.php’);
       
        else
        {
            load_template(TEMPLATEPATH . ‘/search-default.php’);
        }
    }
    else
    {
        load_template(TEMPLATEPATH . ‘/search-default.php’);
    }

    8. Finally the search form:

    <form id="searchform" action="/” method=”get”>
           

           

          
     

                Select Post Type

               
                    Business
                    News
                    LABEL
                    
              

    9. Basicaly when you use this form to submit a search querie,
       WordPress gets name=”post_type” –> ie:   $_GET["post_type"];

    The function then checks if  $_GET["post_type"] has been set,
     if so then loads a template file based on $search_refer = $_GET["post_type"]
    from the /search/ folder we created.  ie. search-xxxxx.php  —>  search-$search_refer.php

    if no template called “search-$search_refer.php” exists then the function uses default-search.php to display search results.

    10. Please commemt if im mistaken.

     

  • Jaypee

    I get a server error trying to implement this :(

    • http://wpsnipp.com Kevin Chard

      what is the error you are getting ?

  • http://twitter.com/pepperzek pepperzek

    Not working for me in 3.3.1. The $s variable is possibly not getting any value. Any suggestions?

    • http://wpsnipp.com Kevin Chard

      Ill test things out in a recent version of wordpress just to make sure although you should not have any issues. I would also suggest updating to 3.4. Ill post back here with the results.

    • http://wpsnipp.com Kevin Chard

      Tested things out and appears to be working fine, did you create the custom template files and have everything setup correctly ?

  • Cosmin

    The code works fine in 3.4.2, but I had to change “post_type” to “posttype”.

    Thanks a lot! :)

  • Keisa

    Is this only for custom post types?

  • Lizy

    Thanks very much! you’ve just made my morning.

  • Silver-monkey

    Well done Sir. Great tip.

  • Tiago

    That returns to me a blank page.. Any help?

  • philhoyt

    I love the idea behind this so clever.
    I do have an issue with pagination though. So renders it sorta useless unless I display all results with a ‘showposts’=>999,

    • philhoyt

      OH SNAP… so I had been working on this for an hour or so b4 i gave up and commented… and then i figured it out…
      Changed the query_posts arg to this

      ‘bio’,
      ‘posts_per_page’ => 10,
      ‘paged’ => $paged,
      );
      query_posts($args);
      ?>

  • dotred

    Thanks for the tip! Works perfect…

  • Rickey

    I was using a child-theme. I had to use { load_template(get_stylesheet_directory() . ‘/template_one-name.php’); }

  • http://www.techdekk.com TechDekk

    Brilliant. Thank you. you ROCK!

  • http://www.techdekk.com TechDekk

    Brilliant. Thank you. you ROCK!

    • http://wpsnipp.com Kevin Chard

      No problem glad you like the snippet!

  • Levente Nagy

    Life saving article,thank you, i was struggling finding a good solution, this helped a lot

    • http://wpsnipp.com Kevin Chard

      No problem glad that we could help!

  • kenan

    if search value is empty , example: ?s=&post_type=products it always returns me results in default template, no metter which post_type I have in search string? any fix for that?

    For example: ?s=+&post_type=products THIS WILL WORK, open in search-products.php
    this: ?s=&post_type=products WILL NOT WORK, open in search-post.php

  • kenan

    if search value is empty , example: ?s=&post_type=products it always returns me results in default template, no metter which post_type I have in search string? any fix for that?

    For example: ?s=+&post_type=products THIS WILL WORK, open in search-products.php
    this: ?s=&post_type=products WILL NOT WORK, open in search-post.php

  • kenan

    if search value is empty , example: ?s=&post_type=products it always returns me results in default template, no metter which post_type I have in search string? any fix for that?

    For example: ?s=+&post_type=products THIS WILL WORK, open in search-products.php
    this: ?s=&post_type=products WILL NOT WORK, open in search-post.php

    • http://wpsnipp.com Kevin Chard

      I would think your best bet would be to use javascript to require something in the field before they are able to search.

    • http://wpsnipp.com Kevin Chard

      I would think your best bet would be to use javascript to require something in the field before they are able to search.

    • http://wpsnipp.com Kevin Chard

      I would think your best bet would be to use javascript to require something in the field before they are able to search.

jqsnipp.com | we just launched jquery snippets website