How To Limit WordPress To Search By Post Titles Only

Limiting WordPress Search Results To Only Posts Titles

WordPressBy Default the standard WordPress search function will restrict results to include the content of your WordPress website as well as post titles. The standard search function is also formatted to include recent posts at the top of the search query.

This can sometimes make it difficult for visitors to find correct results on your WordPress website, especially if your website contains older posts which are (being searched for and) displayed as an anchor text link in more recent posts.

  • To change your WordPress search results from including post content and limiting the WordPress search results on your WordPress blog or website (to include only post titles)  utilize the search_by_title_only function.

Down Copy and paste the snippet below into your functions.php file.
[Normal_Box]


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 );

[/Normal_Box]

Sean Doyle

Sean is a distinguished tech author and entrepreneur with over 20 years of extensive experience in cybersecurity, privacy, malware, Google Analytics, online marketing, and various other tech domains. His expertise and contributions to the industry have been recognized in numerous esteemed publications. Sean is widely acclaimed for his sharp intellect and innovative insights, solidifying his reputation as a leading figure in the tech community. His work not only advances the field but also helps businesses and individuals navigate the complexities of the digital world.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.