The default WordPress search functionality is certainly lacking in areas. Although changes were made in 2013 to improve it, there are still a few areas where WordPress could use some help. It is, however, relatively easy to improve WordPress search by adding a few pieces of code. Here, I’ll list some of the methods you could use to make WordPress search better.
Sort by relevance
In older versions of WordPress, search results were sorted by date and not much else. Because this is (at the very least) annoying for websites with a lot of posts, WordPress core introduced a patch that would change the way search results are sorted.
The changes are as followed:
- Results with a full sentence match in the post title are listed first.
- Search results that include all search terms in the title, but not a full sentence match, are listed next.
- Results including any search terms in the title, but not all search terms or a full sentence match, are listed next.
- Finally, search results that include a full sentence match in the post content come last. Within each group, results are further sorted chronologically by publication date.
Improving the interface
Excerpts in search results by WordPress are not exactly great. Unlike Google, the WordPress search omits emphasis of the keyword if it found matches. Luckily, you can alter parts of the search results and add this feature.
Preparing your theme
In your theme, look for the file that outputs the search results. In this example, it’s a file that I’ve created manually, called
/template-parts/post/content-search.php in a Twenty Seventeen child theme. This file is a copy of
content-excerpt.php that exists in the same directory.
Next, look for the file called
search.php in the theme’s main directory and look for the following line of code:
get_template_part( 'template-parts/post/content', 'excerpt' );
Change this to the following:
get_template_part( 'template-parts/post/content', 'search' );
By making these changes, you’ll ensure that WordPress will use your custom template instead of the default one. Time to add the actual code that will be doing the emphasizing!
functions.php and add the following function:
/** * Adds emphasis to the parts passed in $content that are equal to $search_query. * * @param $content The content to alter. * @param $search_query The search query to match against. * * @return string The emphasized text. */ function emphasize( $content, $search_query ) ', $keys ) .')/iu', '