How to Highlight the Search Terms in Results in WordPress

Welcome to this tutorial this is a sample of what your search will look like after following the steps below.

First open your search.php and look for the following code:

1
<?php the_title(); ?>

Replace the above code with:

1
<?php echo $title; ?>

Make sure that you paste this line above the title code:

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

Now open your CSS file and add the styling for the class search-excerpt, and it will highlight the term. Currently the code is making the search terms bold. You can try this simple CSS in your theme’s stylesheet.

1
2
3
4
strong.search-excerpt {
background-color:yellow;
color:blue;
}

If you have any question drop a comment below.

4 comments

Leave a Reply