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

How To add custom product data tabs in WooCommerce

To add custom product data tabs in WooCommerce, you can use the woocommerce_product_data_tabs and woocommerce_product_data_panels hooks. These hooks allow you to add new tabs to the product edit page in the WooCommerce admin area. Here’s a step-by-step guide on how to achieve this:

Add Custom Taxonomy Filter on Products Dashboard.

How To Filter Products by Taxonomies in the Dashboard?

WooCommerce provide Many Product filters on admin screen , such as “Select a category”, “Filter by product type”, “Filter by stock status”.