Skip to content

Instantly share code, notes, and snippets.

@rafasashi
Created June 26, 2021 06:32
Show Gist options
  • Save rafasashi/74567133c8178b009a831b37c18a8558 to your computer and use it in GitHub Desktop.
Save rafasashi/74567133c8178b009a831b37c18a8558 to your computer and use it in GitHub Desktop.
if( !is_admin() ):
add_filter('pre_get_posts','my_filter_the_search',10,1);
endif;
function my_filter_the_search($query){
$general_site_search = filter_input(INPUT_GET, 's', FILTER_SANITIZE_STRING);
if(!empty($general_site_search)):
add_filter( 'posts_search', '__search_by_title_only', 500, 2 );
endif;
}
function __adapted_search_function($search, $query) {
if(is_admin() || !$query->is_main_query() || !$query->is_search)
return; //determine if we are modifying the right query
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 = 'mcb-product' 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment