How To Limit Search Only In Post Title With Wp_query

Are you looking for a way to limit your search results to post titles? While there may be a plugin for this, we have created a quick code snippet that you can use to limit the search to post titles only in WordPress.

All you have to do is add this code to your theme’s functions.php file or in a plugin file:

function title_filter( $where, &$wp_query ){
    global $wpdb;
    if ( $search_term = $wp_query->get( 'search_kb_title' ) ) {
        $where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql( $wpdb->esc_like( $search_term ) ) . '%\'';
    }
    return $where;
}

In the above code “search_kb_title” is the argument parameter in the Wp_query arguments.

Please refer below code.

$args = array(
  'post_type' 			=> 'kb_article',
  'post_status' 			=> 'publish',
  'search_kb_title'		=> $searchtext,
  'order'				    => 'ASC',
  'orderby'   		    => 'name',
  'posts_per_page'		=> -1,
);

Now we need to apply the filter of created function to the wp_query.

For that, we need to add_filter above the loop of wp_query and needs to remove_filter in after the loop.

As we need to apply this filter for this particular loop only.

add_filter( 'posts_where', 'title_filter', 10, 2 );         
$loop = new WP_Query( $args );
remove_filter( 'posts_where', 'title_filter', 10, 2 );

That’s it now let’s check the results.

1. Results without filter added for search in post_title.

In the above video title without searched text have that word in that post’s content. That’s why it is returned in search results.

2. Results with a filter added for search in post_title.

If you have any queries about this code snippet kindly mention them in the comments.

Submit a Comment

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

Subscribe

Select Categories