[wp-trac] [WordPress Trac] #54853: Search only searching phrases and not searching individual terms

WordPress Trac noreply at wordpress.org
Wed Jan 19 05:27:01 UTC 2022


#54853: Search only searching phrases and not searching individual terms
--------------------------+------------------------------
 Reporter:  jchang        |       Owner:  (none)
     Type:  defect (bug)  |      Status:  new
 Priority:  normal        |   Milestone:  Awaiting Review
Component:  Query         |     Version:  5.8.3
 Severity:  blocker       |  Resolution:
 Keywords:  needs-patch   |     Focuses:
--------------------------+------------------------------

Comment (by parinpanjari):

 The function we check that we are NOT viewing the admin area, that we ARE
 constructing the main query and that we ARE making a search.

 add_filter('posts_search', 'my_search_is_exact', 20, 2);
 function my_search_is_exact($search, $wp_query){

     global $wpdb;

     if(empty($search))
         return $search;

     $q = $wp_query->query_vars;
     $n = !empty($q['exact']) ? '' : '%';

     $search = $searchand = '';

     foreach((array)$q['search_terms'] as $term) :

         $term = esc_sql(like_escape($term));

         $search.= "{$searchand}($wpdb->posts.post_title REGEXP
 '[[:<:]]{$term}[[:>:]]') OR ($wpdb->posts.post_content REGEXP
 '[[:<:]]{$term}[[:>:]]')";

         $searchand = ' AND ';

     endforeach;

     if(!empty($search)) :
         $search = " AND ({$search}) ";
         if(!is_user_logged_in())
             $search .= " AND ($wpdb->posts.post_password = '') ";
     endif;

     return $search;

 }

-- 
Ticket URL: <https://core.trac.wordpress.org/ticket/54853#comment:1>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list