Ship software faster

Search By Default wordpress search functionality will search the entire content of the WordPress post. What if you don't want WordPress to search the entire content of the post, you can actually change the search functionality to only search the post titles.

Copy the following into your functions.php file or create a plugin with this snippet in to make sure WordPress only searches on post title.

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 );
Learn Web Design, Coding & More. No Risk. No Contracts. Learn More

Share the wealth

Keep updated with the latest tutorials and snippets.

Subscribe
Comment