Improving Site Search on WordPress

To enhance the site search on WordPress and add highlighting of searched terms in the search results, follow these steps.

Creating or Editing search.php

If you don’t have a search.php file in your WordPress theme, create it based on index.php. In search.php, we’ll modify how post titles and excerpts are displayed to highlight searched terms.

  1. Creating the search.php fileCreate the search.php file in the root directory of your WordPress theme by copying the content from index.php.
  2. Adding the search results headerAdd the following code at the beginning of search.php to display a header indicating search results:
<h1>Search Results for "<?php echo esc_html($s); ?>"</h1>
  1. This code displays a message to the user that they are on the search results page and shows the searched term.
  2. Editing the post titles display

Find the line in search.php where the post title is outputted using the_title();, and replace it with the following code:

<?php
  $title = get_the_title();
  $keys = explode(" ", $s);
  $title = preg_replace('/('.implode('|', array_map('preg_quote', $keys)) .')/iu', '<strong class="search-excerpt">\0</strong>', $title);
  echo $title;
?>
  1. This code highlights searched terms in post titles.
  2. Editing the post excerpts or content display

Find the line where the post excerpt or content is outputted using the_excerpt(); or the_content();, and replace it with the following code:

<?php
  $excerpt = get_the_excerpt(); // Or use get_the_content() if needed
  $keys = explode(" ", $s);
  $excerpt = preg_replace('/('.implode('|', array_map('preg_quote', $keys)) .')/iu', '<strong class="search-excerpt">\0</strong>', $excerpt);
  echo $excerpt;
?>
  1. his code highlights searched terms in post excerpts or content.Adding styles for highlightingAdd the following CSS code to the style.css file of your theme:css
.search-excerpt {
    background: #ff9; /* yellow background */
    color: #000; /* black text */
}
  1. his CSS code sets a yellow background and black text color for highlighted terms.

Conclusion

Now you have an enhanced search experience on your WordPress site with highlighted searched terms in the search results. This improvement will help users find their desired articles faster and enhance the usability of your site.