Is there a way to limit search to post titles? I know I can modify query.php core file but there must be a way to do it with hooks right?
Thanks in advance!
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Here’s a filter that’ll do the trick. Drop it into your theme’s functions.php or a plugin.
/**
* Search SQL filter for matching against post title only.
*
* @link http://wordpress.stackexchange.com/a/11826/1685
*
* @param string $search
* @param WP_Query $wp_query
*/
function wpse_11826_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', 'wpse_11826_search_by_title', 10, 2 );
Most of the code is just copied from the WP_Query class, except with the post_content LIKE‘s removed.
UPDATE: Removed deprecated like_escape() since 4.0
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0