I am trying to modify the custom wordpress search by using pre_get_posts hook, so that a specific words won't be searched in product description.
add_action( 'pre_get_posts', 'exclude_search_content' );
function exclude_search_content( $Q ) {
$search_phrase = $Q->query['s'];
if( $Q->is_search() ) {
/** Dont search for $search_phrase in excerpt and product description
* search only product title, a meta key and a taxonomy.
*/
}
}
It seems to be more complex than I expected. Any ideas?
if you check posts_search reference you will find some of Contribute already wrote similar function, so i just test it and it's working fine.
function search_by_title_only($search, $wp_query)
{
global $wpdb;
if (empty($search)) {
return $search; // skip processing - no search term in query
}
$q = $wp_query->query_vars;
$n = !empty($q['exact']) ? '' : '%';
$search =
$searchand = '';
foreach ((array) $q['search_terms'] as $term) {
$term = esc_sql($wpdb->esc_like($term));
$search .= "{$searchand}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";
$searchand = ' AND ';
}
if (!empty($search)) {
$search = " AND ({$search}) ";
if (!is_user_logged_in()) {
$search .= " AND ($wpdb->posts.post_password = '') ";
}
}
return $search;
}
add_filter('posts_search', 'search_by_title_only', 20, 2);