24

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!

28

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

  • great works perfectly, I knew there was a filter for this, couldn't find it anywhere in the codex, thanks a lot! – Javier Villanueva 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
  • 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 – PJ Brunet Nov 9 '15 at 23:14

protected by fuxia Aug 5 '12 at 12:41

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

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.