Pawan Kumawat

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 );

 

 

Categories

Related Blogs

To list down future posts in WordPress

To list down future posts in WordPress, you can use the `WP_Query` class to customize the query and fetch future posts. The future posts are the ones with a post status of “future,” and their publication date is scheduled in the future.

WordPress Ajax login

To implement Ajax login in WordPress, you can follow these steps: 1. Open the theme’s functions.php file in your WordPress