Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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!

share|improve this question

1 Answer 1

up vote 14 down vote accepted

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.
 */
function __search_by_title_only( $search, &$wp_query )
{
    global $wpdb;

    if ( empty( $search ) )
        return $search; // skip processing - no search term in query

    $q = $wp_query->query_vars;    
    $n = ! empty( $q['exact'] ) ? '' : '%';

    $search =
    $searchand = '';

    foreach ( (array) $q['search_terms'] as $term ) {
        $term = esc_sql( like_escape( $term ) );
        $search .= "{$searchand}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";
        $searchand = ' AND ';
    }

    if ( ! empty( $search ) ) {
        $search = " AND ({$search}) ";
        if ( ! is_user_logged_in() )
            $search .= " AND ($wpdb->posts.post_password = '') ";
    }

    return $search;
}
add_filter( 'posts_search', '__search_by_title_only', 500, 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 as $wpdb wasn't global!

share|improve this answer
    
great works perfectly, I knew there was a filter for this, couldn't find it anywhere in the codex, thanks a lot! –  javiervd Mar 12 '11 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 Aug 3 '11 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 Aug 4 '11 at 7:32
    
@Ashfame I have revised my answer. –  TheDeadMedic Aug 4 '11 at 12:44
    
Thanks! It works now :) –  Ashfame Aug 4 '11 at 13:31

protected by toscho Aug 5 '12 at 12:41

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

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