how to limit search to post titles?

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!

Related posts

Leave a Reply

1 comment

  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