posts_search (ok)

function __adapted_search_function($search, $query) {
  if(is_admin() || !$query->is_main_query() || !$query->is_search) return;
  global $wpdb;
  $search_term = $query->get('s');
  $search = ' AND (';
  //point 1
  $search .= "($wpdb->posts.post_title LIKE '%$search_term%')";
  //need to add an OR between search conditions
  $search .= " OR ";
  //point 2
  $search .= "($wpdb->posts.post_excerpt LIKE '%$search_term%')";
  //need to add an OR between search conditions
  $search .= " OR ";
  //point 3
  $search .= "($wpdb->postmeta.meta_key = 'test' AND $wpdb->postmeta.meta_value LIKE '%$search_term%')";
  //add the filter to join, sql will error out without joining the tables to the query
  add_filter('posts_join', '__custom_join_tables');   
  return $search . ') ';
}
function __custom_join_tables($joins) {
  global $wpdb;
  $joins = "JOIN $wpdb->postmeta ON ($wpdb->postmeta.post_ID = $wpdb->posts.ID)";
  return $joins;
}
add_action('posts_search', '__adapted_search_function',1,2);

Kết quả: http://localhost/reset/?s=zgfdfdfdfdfdfgzgfdfdfdfdfdfg134

Sử dụng thêm posts_groupby kết quả không bị lặp lại :) http://localhost/reset/?s=a

function __adapted_search_function($search, $query) {
  if(is_admin() || !$query->is_main_query() || !$query->is_search) return;
  global $wpdb;
  $search_term = $query->get('s');
  $search = ' AND (';
  //point 1
  $search .= "($wpdb->posts.post_title LIKE '%$search_term%')";
  //need to add an OR between search conditions
  $search .= " OR ";
  //point 2
  $search .= "($wpdb->posts.post_excerpt LIKE '%$search_term%')";
  //need to add an OR between search conditions
  $search .= " OR ";
  //point 3
  $search .= "($wpdb->postmeta.meta_key = 'test' AND $wpdb->postmeta.meta_value LIKE '%$search_term%')";
  //add the filter to join, sql will error out without joining the tables to the query
  add_filter('posts_join', '__custom_join_tables');   
  add_filter( 'posts_groupby', 'my_posts_groupby' );
  return $search . ') ';
}
function my_posts_groupby($groupby) {
    global $wpdb;
    $groupby = "{$wpdb->posts}.ID";
    return $groupby;
}
function __custom_join_tables($joins) {
  global $wpdb;
  $joins = "JOIN $wpdb->postmeta ON ($wpdb->postmeta.post_ID = $wpdb->posts.ID)";
  return $joins;
}
add_action('posts_search', '__adapted_search_function',1,2);

Last updated