This code modifies WordPress’s default search functionality to only return posts where the search term is found in the post titles, excluding results based on content, excerpts, or other fields.
function ts_search_by_title( $search, $wp_query ) {
if ( ! empty( $search ) && ! empty( $wp_query->query_vars['search_terms'] ) ) {
global $wpdb;
$q = $wp_query->query_vars;
$n = ! empty( $q['exact'] ) ? '' : '%';
$search = array();
foreach ( ( array ) $q['search_terms'] as $term )
$search[] = $wpdb->prepare( "$wpdb->posts.post_title LIKE %s", $n . $wpdb->esc_like( $term ) . $n );
if ( ! is_user_logged_in() )
$search[] = "$wpdb->posts.post_password = ''";
$search = ' AND ' . implode( ' AND ', $search );
}
return $search;
}
add_filter( 'posts_search', 'ts_search_by_title', 10, 2 );
Related Posts:
How to Use WP_Query to Fetch and Display Custom…
How to Create a Search Form For Custom Fields in WordPress?
How to use AJAX in WordPress: A Step-by-Step Guide
How to Create a Custom WordPress Login Page?
Including only Custom Post Types in WordPress Search Results
How to Automatically Delete WordPress Posts Older…