If you want to customize the query when doing a search in WordPress – when meta_queries are not enough.
The custom “WHERE” part of the query
function custom_where($where,$query) { global $wpdb; $new_where = " /*my new where*/ $wpdb->postmeta.meta_value LIKE '%".get_search_query()."%'"; if (empty($where)) $where = $new_where; else $where = "{$where} /*OR*/ OR {$new_where}"; return $where; } |
The “DISTINCT” part
function search_distinct() { return "DISTINCT"; } |
The custom “JOIN”
function custom_join($join) { global $wp_query, $wpdb; $join .= "INNER JOIN $wpdb->postmeta ON $wpdb->posts.ID = $wpdb->postmeta.post_id "; return $join; } |
Putting them all up for the “pre_get_posts”
function filter_search($query) { if ($query->is_search) { $query->set('post_type', array('post', 'recipes')); add_filter('posts_where','custom_where'); add_filter('posts_join', 'custom_join'); add_filter('posts_distinct', 'search_distinct'); } //var_dump($query); return $query; }; add_filter('pre_get_posts', 'filter_search'); |