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

Adding Sidebar In WordPress Theme

Adding a sidebar to a WordPress theme involves modifying the theme files and registering a new sidebar area using WordPress functions. Below are the general steps to add a sidebar in WordPress themes:

WooCommerce: Get Product Info (ID, SKU, $) From $product Object

In WooCommerce, the `$product` object represents a single product, and it contains various information and methods that you can access to get details about the product. Here is a list of common product information that you can retrieve from the `$product` object: