How To Limit Search To Only Post Titles?

To limit the search in WordPress to only post titles, you can modify the main search query using the `posts_search` filter. Here’s an example of how you can achieve this:

1. Open the theme’s functions.php file in your WordPress theme directory.
2. Add the following code to the file:

 

function limit_search_to_post_titles($search, $wp_query) {
    if (is_search() && !is_admin()) {
        $search_terms = $wp_query->query_vars['s'];
        
        if (!empty($search_terms)) {
            global $wpdb;
            
            // Modify the search query to search only in post titles
            $search = $wpdb->prepare(" AND {$wpdb->posts}.post_title LIKE %s", '%' . $wpdb->esc_like($search_terms) . '%');
        }
    }
    
    return $search;
}
add_filter('posts_search', 'limit_search_to_post_titles', 10, 2);

 

3. Save the changes and upload the modified functions.php file back to your server.

This code adds a filter to the `posts_search` hook, which allows you to modify the SQL query’s search condition. It modifies the search query to include a condition that searches for the given search terms only in the post titles.

After making these changes, when performing a search in WordPress, the search results will be limited to only include posts whose titles match the search terms, excluding other content such as pages or post content.

[TheChamp-Sharing]

Related Blogs

Customize Woocommerce Settings Tab

Let’s talk about customizing Woocommerce Admin setting Tabs.To hide a specific Woocommerce setting tab or want to customize the Woocommerce setting tabs, not the entire sub-menu, but just a tab.For just Removing tabs we can use

Request A Quote

Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.