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
function __search_by_title_only(*
* @param string $search,
&$wp_query* )@param WP_Query $wp_query
{ */
function wpse_11826_search_by_title( $search, $wp_query global) $wpdb;
{
if ( ! empty( $search ) )
&& ! empty( $wp_query->query_vars['search_terms'] ) ) {
return $search; // skip processing - noglobal search$wpdb;
term in query
$q = $wp_query->query_vars;
$n = ! empty( $q['exact'] ) ? '' : '%';
$search =
$searchand$search = '';array();
foreach ( ( array ) $q['search_terms'] as $term ) {
$term = esc_sql( like_escape( $term ) );
$search$search[] .= "{$searchand}($wpdb->prepare( "$wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";
%s", $n . $wpdb->esc_like( $searchand$term =) '. AND$n ';);
}
if ( ! emptyis_user_logged_in( $search ) ) {
$search = " AND ({$search}) ";
if$search[] (= !"$wpdb->posts.post_password is_user_logged_in()= )''";
$search = ' AND $search' .= "implode( ' AND ($wpdb->posts.post_password', =$search '') ";;
}
return $search;
}
add_filter( 'posts_search', '__search_by_title_only''wpse_11826_search_by_title', 50010, 2 );
Most of the code is just copied from the WP_Query
class, except with the post_content LIKE
's removed.
UPDATE: This code has been updated for WordPress 3.2.1. I'm surprised it even worked before asRemoved deprecated $wpdblike_escape()
wasn't global!since 4.0