Family Encyclopedia >> Electronics

How to Highlight Search Terms in WordPress Search Results: A Proven Guide

Enhance your WordPress site's search experience by highlighting matching terms in results. As experienced developers, we've implemented this for clients to make searches more intuitive and user-friendly. Here's our step-by-step guide.

How to Highlight Search Terms in WordPress Search Results: A Proven Guide

Open your theme's search.php file and locate the main loop where results are displayed—typically around while (have_posts()).

Before the post title output (e.g., the_title()), insert this code:

<?php $title = get_the_title(); $search_query = get_search_query(); $keys = explode(' ', $search_query); $title = preg_replace('/('.preg_quote(implode('|', $keys), '/').')/iu', '<strong class="search-excerpt">\0</strong>', $title); ?>

Replace the original title echo with: <?php echo $title; ?>.

Add this CSS to your theme's stylesheet for yellow highlighting with blue text:

strong.search-excerpt {
  background-color: yellow;
  color: blue;
}

Source: Adapted from Michael Martin. Test thoroughly, and backup your files first.