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

Cron Job WordPress (WP-Cron)

What Is Wordpress Cron Job? Wordpress Cron Job is how WordPress handles scheduling time-based tasks in WordPress.“Cron” Means the cron time-based task scheduling system which is available on UNIX systems.

Programmatically Remove Product From Cart Using Product Id

Want to remove specific WooCommerce product from a cart?
WooCommerce provide ‘WC()->cart->remove_cart_item(string $cart_item_key)’ function to remove a product from cart. if we go through WooCommerce Documentation , wewill find that it accepts cart_item_key as parameter.

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