Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress: WP_Query how to apply search criteria with custom post type

I have a custom post type, photo, and need to search for photos matching the title or description with the search keyword with various criteria: contains LIKE %$search_term%, starts with LIKE $search_term% etc. I have the following query, but this doesn't filter records according to $search_term. Please direct me to the right direction to embed this requirement with this query.

$search_term = $_GET['term'];
$search_criteria = $_GET['type'];

$loop = new WP_Query( array(
    'post_type' => 'photo',
    'posts_per_page' => 12,
    'orderby'=> 'post_date'
));

Please be nice with me, I am a newbie in Wordpress and don't even know if I am asking a foolish question. But I am really stuck with it and need a solution. Any help will be appreciated a lot. Thank you everybody.

like image 568
Samik Chattopadhyay Avatar asked Dec 02 '11 15:12

Samik Chattopadhyay


2 Answers

Add the "s" key to your existing arguments array:

$loop = new WP_Query( array(
    'post_type' => 'photo',
    'posts_per_page' => 12,
    'orderby' => 'post_date',
    's' => 'search_term'
));

Documentation can be found at: http://codex.wordpress.org/Class_Reference/WP_Query#Search_Parameter

like image 54
Prakash Raman Avatar answered Sep 19 '22 17:09

Prakash Raman


Pass your search string here example like this ( 's'=>'test' )

 <?php

 /*pass your search string here example like this ( 's'=>'test' ) */
 $args=array('s'=>'test','order'=> 'DESC', 'posts_per_page'=>get_option('posts_per_page'));

   $query=new WP_Query($args);

  if( $query->have_posts()): 

  while( $query->have_posts()): $query->the_post();

 {
   echo $post->post_title;
   echo $post->post_content;
 }

 endwhile; 
 else:
 endif;

 ?>
like image 27
RichestSoft Avatar answered Sep 17 '22 17:09

RichestSoft