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.