How to exclude post body from WP search

To remove elements from being searched, use the post_search filter to amend the SQL query for the search e.g. only pull in the title.

function ni_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( 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', 'ni_search_by_title_only', 500, 2 );

Taken from https://nathaningram.com/restricting-wordpress-search-to-titles-only/

Personally I prefer a plugin for this as it gives me full control over every field I want in my search, the one I use is relevanssi. It should do what you want really easily.

Leave a Comment