How to Highlight the Search Terms in Results in WordPress

How to Highlight Search Terms in WordPress Results (2024 Guide)

Are you looking to improve the user experience of your WordPress website‘s search functionality? One effective technique is to highlight the visitor‘s search terms when displaying the results. By making the queried keywords stand out, you help users quickly scan the page and locate the most relevant information.

In this expert guide, we‘ll walk you through the process of highlighting search terms in your WordPress search results. Whether you‘re running the latest version or an older release, these steps will work for you. Let‘s dive in!

Benefits of Highlighting Search Terms
Before we get into the technical details, let‘s consider why you might want to highlight search terms in the first place:

  • Enhanced User Experience: When a visitor searches your site, they‘re looking for something specific. Highlighting their search terms in the results provides immediate visual feedback and confirms that your site has relevant content. This improved experience can lead to longer visits and higher engagement.

  • Faster Scanning: With the relevant terms standing out, users can rapidly scan the search results to find the best matches for their query. This saves time and reduces frustration, especially on mobile devices where screen space is limited.

  • SEO Benefits: When visitors can easily find what they‘re looking for, they‘re more likely to view your site as a valuable resource. This positive experience can translate to lower bounce rates, more backlinks, and ultimately better search engine rankings.

Now that we understand the benefits, let‘s look at how to implement search term highlighting on your WordPress site.

Step 1: Modify the Search Template File
WordPress generates search results using the search.php template file. To highlight the search terms, we need to modify this file:

  1. Access your WordPress site‘s file system via FTP/SFTP or your hosting provider‘s file manager.
  2. Navigate to your active theme‘s folder, usually located at /wp-content/themes/your-theme/.
  3. Look for the search.php file. If it doesn‘t exist, you can create one by copying index.php and renaming the copy.
  4. Download a backup of the search.php file before making changes, just in case.
  5. Open search.php for editing.

Step 2: Locate and Modify the Title Output
With search.php open, find the part of the template that outputs the title of each search result. Depending on the theme, this will look something like:

<?php the_title(); ?>

To prepare for our highlighting code, we‘ll replace this with:

<?php echo $title; ?>

This change will let us modify the $title variable before outputting it.

Step 3: Retrieve the Search Terms
Now we need to retrieve the visitor‘s search query and split it into individual keywords. Paste this code above the line you modified in step 2:

<?php
$search_query = get_search_query();
$search_terms = explode(" ", $search_query);
?>

The get_search_query() function retrieves the search string, and explode() splits it into an array of terms by spaces.

Step 4: Highlight the Search Terms in the Title
With the search terms stored in $search_terms, we can use PHP‘s preg_replace() function to find and highlight them in the result titles. Add this code after the previous addition:

<?php
$title = get_the_title();
$highlighted_title = preg_replace(‘/(‘.implode(‘|‘, $search_terms) .‘)/iu‘, ‘<mark>$0</mark>‘, $title);
?>

Here‘s what this code does:

  • get_the_title() retrieves the original title of the search result.
  • implode(‘|‘, $search_terms) combines the search terms into a regular expression alternation, like term1|term2|term3. The | means "or".
  • The /iu flags at the end of the regex make it case-insensitive and Unicode-aware.
  • preg_replace() searches the title for any of the search terms. When it finds a match, it wraps the term in <mark> tags to highlight it.
  • The highlighted title is stored in $highlighted_title.

Finally, update the title output to use the highlighted version:

<?php echo $highlighted_title; ?>

Step 5: Style the Highlighted Terms with CSS
The <mark> tag has default styling that should make the search terms stand out. However, you can customize the styling to better fit your theme.

Open your theme‘s stylesheet, often named style.css. If you don‘t have one, create it in your theme‘s folder. Add this CSS rule:

mark {
background-color: yellow;
color: black;
}

Feel free to adjust the colors or add other properties like padding, border-radius, and font-weight to achieve the desired effect.

Step 6: Handle Partial Matches and Other Edge Cases
The basic preg_replace() usage will match and highlight complete words only. If you want to highlight partial word matches too, modify the regex like this:

‘/(‘.implode(‘|‘, $search_terms) .‘)/iu‘

For example, if the visitor searches for "word", it would highlight "WordPress" too.

To keep the highlights on exact word matches only, use the special regex word boundary character \b:

‘/\b(‘.implode(‘|‘, $search_terms) .‘)\b/iu‘

This ensures only complete search terms are highlighted.

Another consideration is how to handle special characters in the search query. By default, preg_replace() will interpret characters like periods and parentheses as part of the regex pattern. To avoid issues, use preg_quote() to escape the search terms:

$search_terms = array_map(‘preg_quote‘, $search_terms);

After this change, a search for "WordPress (CMS)" will highlight correctly.

Step 7: Consider SEO and Performance
While highlighting search terms enhances the user experience, it‘s important to consider the SEO implications and performance impact.

From an SEO perspective, the highlighted terms can reinforce to search engines that your content is relevant to those keywords. This is a positive signal. However, be careful not to overdo it – if every other word is highlighted, it may appear spammy to both visitors and search engine crawlers.

In terms of performance, the highlighting code will slightly increase the server load for each search query. This is usually negligible, but if your site receives a high volume of searches, you may want to implement caching.

Plugins like WP Rocket and WP Super Cache can store rendered search results pages and serve them quickly without running the highlighting code each time. You can also utilize server-side caching solutions like Varnish or Nginx FastCGI Cache.

Advanced Tip: Highlight Search Terms in Excerpts
In addition to highlighting terms in the search result titles, you may also want to highlight them in the excerpts or post content previews.

To do this, locate the part of your search template that displays the excerpt. It will typically use the_excerpt() or wp_trim_words() functions.

Replace the function call with custom code to retrieve the post content, strip HTML tags, trim it to the desired length, and apply the preg_replace() highlighting:

<?php
$excerpt = wp_strip_all_tags(get_the_content());
$excerpt = wp_trim_words($excerpt, 55, ‘…‘);
$highlighted_excerpt = preg_replace(‘/\b(‘.implode(‘|‘, $search_terms) .‘)\b/iu‘, ‘<mark>$0</mark>‘, $excerpt);
echo $highlighted_excerpt;
?>

This code retrieves the full post content, removes HTML tags, trims it to 55 words, and highlights any search terms in the resulting excerpt. Adjust the word count to your liking.

Keep in mind that this method will load and process the full content of each search result, which can impact performance more than just highlighting titles. Make sure to implement caching if you go this route.

Conclusion
Highlighting search terms is a proven way to improve the user experience and satisfaction with your WordPress site‘s search feature. By following the steps in this guide, you can implement it on your own site in a search-engine-friendly and performance-conscious way.

To recap:

  1. Modify the search.php template file to prepare for highlighting
  2. Use PHP to retrieve the search query and split it into terms
  3. Find and highlight search terms in the result titles with preg_replace()
  4. Style the highlights with CSS to match your theme
  5. Handle partial matches, special characters, and other edge cases
  6. Consider the SEO benefits and performance implications
  7. Optionally highlight terms in excerpts or post previews

I hope this in-depth tutorial helps you enhance your WordPress search functionality for 2024 and beyond. Remember to test thoroughly and consider implementing caching if you anticipate a high volume of searches.

Happy coding!

Did you like this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.