How To Limit WordPress To Search By Post Titles Only
Limiting WordPress Search Results To Only Posts Titles
By Default the standard WordPress search function will restrict results to include the content of your WordPress website as well as post titles. The standard search function is also formatted to include recent posts at the top of the search query.
This can sometimes make it difficult for visitors to find correct results on your WordPress website, especially if your website contains older posts which are (being searched for and) displayed as an anchor text link in more recent posts.
- To change your WordPress search results from including post content and limiting the WordPress search results on your WordPress blog or website (to include only post titles) utilize the search_by_title_only function.
Copy and paste the snippet below into your functions.php file.
[Normal_Box]
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( 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', 'search_by_title_only', 500, 2 );
[/Normal_Box]