Using Searchform to Search Keyword on WordPress Title only

You are currently viewing Using Searchform to Search Keyword on WordPress Title only

Using Searchform to Search Keyword on WordPress Title only

When using WordPress search, sometime it will show a bunch of un-relevent posts. If you are running a 1000+ posts blog, you definitely want your users to search the exact match to their search keyword string so they won’t stray away from your site if they saw unrelated search results.

Here’s a easy and simple snippet that can help you target WordPress Title only in search query. Add this code to your functions.php

[php]if( !function_exists(‘wp_search_by_title_only’) ):
function wp_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( like_escape( $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’, ‘wp_search_by_title_only’, 500, 2 );
endif;[/php]

You can also filtered out ‘Page’ from search result

[php]if( !function_exists( ‘remove_page_search_filter’ )):
function remove_page_search_filter($query) {
if ($query->is_search) {
$query->set(‘post_type’, ‘post’);
}
return $query;
}
add_filter(‘pre_get_posts’,’remove_page_search_filter’);
endif;[/php]

[notice type=”error”]Please note: if you want to include Custom Post Type also know as CPT in search result just use below code instead[/notice]

[php]if( !function_exists( ‘remove_page_search_filter’ )):
function remove_page_search_filter($query) {
if ($query->is_search) {
$query->set(‘post_type’, array(‘post’, ‘myCPT1’, ‘myCPT2, ‘myCPT3’));
}
return $query;
}
add_filter(‘pre_get_posts’,’remove_page_search_filter’);
endif;[/php]
Now all your search will be targeting the keyword in your WordPress post title only and exclude pages. You can test our search form on top header for a better understanding.