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

Add same product to cart twice instead of changing quantity in Cart

By default, WooCommerce allows customers to change the quantity of a product in the cart by updating the quantity input field on the cart page. If the quantity is increased, the product will be added to the cart only once with the updated quantity. However, if you want to allow customers to add the same product multiple times as separate items in the cart, you’ll need to customize the cart behavior.

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.