Searching

Restricting WordPress Search to Titles Only

Yes, WordPress search leaves a lot to be desired. But with some tweaking, you can get the results you want.

Why would you want to do that?

In a recent project, the client requested that WordPress search return only hits from page titles and ignore page and post content. Why would they request this, you might ask? In a site that is heavily optimized for SEO, a popular keyword search might return dozens of hits that are not really what the user needs to see. By restricting search results to page or post title only, many extraneous matches can be filtered out.

Certainly opting to restrict searches to title only can hinder search capabilities as well. It should be used sparingly and only on sites that have been written with SEO keywords in mind.

The Code

Adding the following code to your active theme’s functions.php file will restrict WordPress search results to page and post titles only.

[sourcecode language=”php”]
//Limit Search to Post Titles Only

function ni_search_by_title_only( $search, &$wp_query )
{
global $wpdb;
if ( empty( $search ) )
return $search; // skip processing – no search term in query
$q = $wp_query->query_vars;
$n = ! empty( $q[‘exact’] ) ? ” : ‘%’;
$search =
$searchand = ”;
foreach ( (array) $q[‘search_terms’] as $term ) {
$term = esc_sql( like_escape( $term ) );
$search .= "{$searchand}($wpdb->posts.post_title LIKE ‘{$n}{$term}{$n}’)";
$searchand = ‘ AND ‘;
}
if ( ! empty( $search ) ) {
$search = " AND ({$search}) ";
if ( ! is_user_logged_in() )
$search .= " AND ($wpdb->posts.post_password = ”) ";
}
return $search;
}
add_filter( ‘posts_search’, ‘ni_search_by_title_only’, 500, 2 );[/sourcecode]

Excluding Certain Particular Pages from WordPress Search

If you want to further tweak your search results, you can manually exclude certain pages from being returned by WordPress search by using the code below. FYI, this code is not related to the code above and can be used independently of it. It should also be added to the functions.php file in your active child theme.

[sourcecode language=”php”]

function ni_search_filter( $query ) {
if ( $query->is_search && $query->is_main_query() ) {
$query->set( ‘post__not_in’, array( 80, 147, 13 ) );
}
}
add_filter( ‘pre_get_posts’, ‘ni_search_filter’ );[/sourcecode]

You will need to add the specific page or post IDs you want to eliminate from search on line 3 of the code above.

If you don’t know how to find the ID of a page or post, install the Simply Show IDs plugin which displays ID numbers on the page and post list screens. By the way, don’t let the fact that the plugin hasn’t been updated in a while dissuade you. If a plugin works, there’s not need for it to be updated.