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.

Related Blogs

Elementor shortcodes

Elementor is a popular page builder plugin for WordPress that allows you to create and customize web pages using a drag-and-drop interface. Elementor provides a wide range of built-in widgets and elements, and you can also create your own custom elements using shortcodes.

WooCommerce: Display Regular & Sale Price @ Cart Table

Learn how to enhance your WooCommerce cart table by displaying both the regular and sale prices. Implement this functionality using WordPress hooks and filters to provide clear and appealing pricing information to your customers, encouraging sales and improving the shopping experience.

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.