Limit WordPress Search to Post Titles Only

Code Snippets Coding Blog PHP PHP Development Plugins Theme Optimization Woocommerce WooCommerce Customization WooCommerce Development Woocommerce Hooks WooCommerce Tips Wordpress WordPress Development WordPress Hacks WordPress Tips WP Best Practices

Limit WordPress Search to Post Titles Only Tutorial/Guide

To restrict WordPress search results to only include post titles, you can customize the main query using the posts_search filter. Follow these steps:

  1. Access your WordPress theme folder and open the functions.php file.
  2. Insert the code snippet below into 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;
            $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);

Once saved, your WordPress search will only return posts whose titles contain the searched keywords, ignoring content from body text or other areas.  

💡 Have a Coding Problem?

Search our archives or reach out to our team for solutions and expert advice.