Wordpress Snippets

Limit WordPress To Perform Search Through Post Titles Only

On a project, sometimes you may require WordPress to perform search through post titles only and exclude post content as well as post excerpts. Although it’s not very useful to exclude post content from searches because then you will get less relevant results and also less results in quantity, but on a special project you might want this unique feature. So in this topic I will post a way to perform search through post titles only.

We can achieve this with standard posts_search WordPress filter. With this filter we can modify the default behavior of search in WordPress. First we will check if search returns empty results and in that case, we will skip the process any further. But in case of non-empty search results, we will run SQL query to match keywords against post title and return the results accordingly. So following is the function to search through post titles only. You must add this WordPress code snippet in your theme’s functions.php file to apply search filter.

// search filter for searching through post titles only
function wcs_search_by_title_only( $search, &$wp_query ) {

    global $wpdb;

    if ( empty( $search ) )
        return $search;

    $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', 'wcs_search_by_title_only', 500, 2 );

Hire Us. Or just say Hi!
Need a job? Apply to get one.