Posted By

depiction on 03/27/13


Tagged

search post wordpress type types BY custom


Versions (?)

WordPress: Search Posts by Custom Post Type


 / Published in: PHP
 

URL: http://wpsnipp.com/index.php/template/create-multiple-search-templates-for-custom-post-types/

Add the ability to search posts by custom post types.

  1. There are two options:
  2.  
  3.  
  4. 1.
  5.  
  6. 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.
  7.  
  8. <?
  9. $search_refer = $_GET["post_type"];
  10. if ($search_refer == 'CUSTOM_POST_TYPE') { load_template(TEMPLATEPATH . '/template_one-name.php'); }
  11. elseif ($search_refer == 'CUSTOM_POST_TYPE') { load_template(TEMPLATEPATH . '/template_two-name.php'); };
  12. ?>
  13.  
  14.  
  15. 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.
  16.  
  17. <?php
  18. $args = array(
  19. 'post_type'=> 'CUSTOM_POST_TYPE',
  20. 's' => $s);
  21. query_posts($args);
  22. ?>
  23.  
  24.  
  25. Search form
  26.  
  27. 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.
  28.  
  29. <form id="searchform" action="<?php bloginfo('home'); ?>/" method="get">
  30. <input id="s" maxlength="150" name="s" size="20" type="text" value="" class="txt" />
  31. <input name="post_type" type="hidden" value="CUSTOM_POST_TYPE" />
  32. <input id="searchsubmit" class="btn" type="submit" value="Search" />
  33. </form>
  34.  
  35.  
  36.  
  37. 2. First, add the following to a new search form:
  38.  
  39. <input type="hidden" name="post_type" value="custom-post-type-name" />
  40.  
  41. Then in the theme's functions.php file, add the following:
  42.  
  43. // Add support for searching by custom post types.
  44. function mySearchFilter($query) {
  45. $post_type = $_GET['post_type'];
  46. if (!$post_type) {
  47. $post_type = 'any';
  48. }
  49. if ($query->is_search) {
  50. $query->set('post_type', $post_type);
  51. };
  52. return $query;
  53. };
  54.  
  55. add_filter('pre_get_posts','mySearchFilter');

Report this snippet  

You need to login to post a comment.