WordPress Snippets at WPcustoms

Limit Seach to Post Titles

This code limits the WordPress search to check only the post title for the searched term. You can also modify that to the excerpt by replacing $wpdb->posts.post_title to other things like the excerpt or authors.


/**
 * Snippet Name: Limit Seach to Post Titles
 * Snippet URL: https://wpcustoms.net/snippets/limit-seach-to-post-titles/
 */
  function wpc_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', 'wpc_search_by_title_only', 500, 2 );