Home » Web Design » How To Limit WordPress To Search By Post Titles Only

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]

Jared Harrison

Jared Harrison is an accomplished tech author and entrepreneur, bringing forth over 20 years of extensive expertise in cybersecurity, privacy, malware, Google Analytics, online marketing, and various other tech domains. He has made significant contributions to the industry and has been featured in multiple esteemed publications. Jared is widely recognized for his keen intellect and innovative insights, earning him a reputation as a respected figure in the tech community.

More Reading

Post navigation

Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

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

How To Display User And Visitor IP Addresses On WordPress Using Shortcodes

How to create a WordPress Archive page

How To Install WordPress Themes