How To Limit Search To Post Titles?

We have many question regarding search functionality of WordPress

  1. I added a text field to the posts filter form and I use s= parameter to make the search work. But how to search only in the title of the post (not in the content)?
  2. how to limit search to post titles?
  3. How to search only by Post Title?

Answer is very simple  using “posts_search” filter.

Usually when we use search option it searches in post title and post content both . but ion some conditions we need to search only in post content or only in post title..

For this we need to modify “posts_search” filter. This filter called every time when any loop is called . or any other query for getting post data’s and posts.

 

function custum_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', 'custum_search_by_title_only', 500, 2 );

 

 

Leave a Comment

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