Advertisement
Guest User

custom search

a guest
Sep 3rd, 2013
729
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.33 KB | None | 0 0
  1. if( !is_admin() ):
  2.     add_filter('pre_get_posts','my_filter_the_search',10,1);
  3. endif;
  4.  
  5. function my_filter_the_search($query){
  6.  
  7.     $general_site_search = filter_input(INPUT_GET, 's', FILTER_SANITIZE_STRING);
  8.  
  9.     if(!empty($general_site_search)):
  10.         add_filter( 'posts_search', '__search_by_title_only', 500, 2 );
  11.     endif;
  12. }
  13.  
  14. function __adapted_search_function($search, $query) {
  15.   if(is_admin() || !$query->is_main_query() || !$query->is_search)
  16.     return; //determine if we are modifying the right query
  17.  
  18.   global $wpdb;
  19.   $search_term = $query->get('s');
  20.   $search = ' AND (';
  21.  
  22.   //point 1
  23.   $search .= "($wpdb->posts.post_title LIKE '%$search_term%')";
  24.  
  25.   //need to add an OR between search conditions
  26.   $search .= " OR ";
  27.  
  28.   //point 2
  29.   $search .= "($wpdb->posts.post_excerpt LIKE '%$search_term%')";
  30.  
  31.   //need to add an OR between search conditions
  32.   $search .= " OR ";
  33.  
  34.   //point 3
  35.   $search .= "($wpdb->postmeta.meta_key = 'mcb-product' AND $wpdb->postmeta.meta_value LIKE '%$search_term%')";
  36.  
  37.   //add the filter to join, sql will error out without joining the tables to the query
  38.   add_filter('posts_join', '__custom_join_tables');
  39.  
  40.   return $search . ') ';
  41. }
  42.  
  43. function __custom_join_tables($joins) {
  44.   global $wpdb;
  45.   $joins = "JOIN $wpdb->postmeta ON ($wpdb->postmeta.post_ID = $wpdb->posts.ID)";
  46.   return $joins;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement