How to search by title or tags exclusively?

I would like to modify the default search query of WordPress to be able to get results from searching exclusively by tags or title. Meaning, it would show posts that contains a match from either the title or the tags. It would also completely ignore any match found inside the posts contents.

I have tried implementing it with this code:

function __search_by_title_only( $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($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’, 500, 2);

Problem: It only searches exclusively for title and does not include any resulting matches for tags. I tried to use the “Search Everything” plugin for searching by tags. The plugin works stand alone but completely gets ignored when used together with the code above.

Read more here:: How to search by title or tags exclusively?

Leave a Reply

Your email address will not be published. Required fields are marked *