In this blog we will learn about how to restrict WordPress to search by title only.
// Customise search query to search by post title and then remove it after this query.
add_filter( 'posts_where', 'my_title_filter, 10, 2 );
$latest_post_ids = new WP_Query( $args );
remove_filter( 'posts_where', 'my_title_filter );
function title_filter( $where, &$wp_query ) {
global $wpdb;
if ( $search_term = $wp_query->get( 'search_post_title' ) ) {
$where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . $wpdb->esc_like( $search_term ) . '%\'';
}
return $where;
}
We can hook into WordPress using `posts_where` hook and then modify the query to search by post title using `post_title LIKE`
You can watch the above video for the demo.

Leave a Reply