How to Highlight the Search Terms in Results in WordPress

Posted on February 16th, 2010 by in Tutorials | 3 Comments  
How to Highlight the Search Terms in Results in WordPress

In an attempt to make your WordPress search even more user friendly, you can highlight the search terms in the results. We did this for one of our clients, so we thought it would be useful for other users. In this article we will show you how you can highlight search terms in the results in WordPress.

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

<?php the_title(); ?>

Replace the above code with:

<?php echo $title; ?>

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

<?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.

Source: Michael Martin

About

Editorial Staff at WPBeginner mainly Syed and David.

Post comment as twitter logo facebook logo
Sort: Newest | Oldest

You should add a little example image on every tutorial, that would be more understandable (:

Nice tutorial. And for those wo want to make some highlight with colors they must define their css class as div.highlight
and replace the code with
And that`s alll. Thanks and have fun.

Very helpful tutorial, will use it later on :)
Thanks for sharing!

Tweets about us: