29

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!

1 Answer 1

38

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

8
  • great works perfectly, I knew there was a filter for this, couldn't find it anywhere in the codex, thanks a lot! Commented Mar 12, 2011 at 16:19
  • @TheDeadMedic I just tried it on my blog and that particular query now returns no result at all, with or without this code. Any ideas?
    – Ashfame
    Commented Aug 3, 2011 at 23:37
  • Now its working as usual without the code but the code didn't work for me. It showed the same results :/
    – Ashfame
    Commented Aug 4, 2011 at 7:32
  • 1
    Thank you, it works fine, if you remove {$n}s near {$term} it makes exact search. But there is a problem it doesn't seach terms with blank like"apple juice". But it seaches apple.
    – user11192
    Commented Dec 16, 2011 at 12:12
  • 1
    PHP message: PHP Fatal error: Call to undefined method wpdb::esc_like() --- If you have an older WordPress, this is a new function as of WP 4.0
    – Jay Brunet
    Commented Nov 9, 2015 at 23:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.