How to Highlight the Search Terms in Results in WordPress
Today, We will share how you can highlight search terms in the results in WordPress. We highlight things to attract people towards it as it readily grabs attention. Moreover, It makes WordPress search more user-friendly.
What is Highlighting?
It is the process or action of making a text/ object stand out from the rest of the text/object on the display screen.
When you google any word or text, google represents the searched term in the results in a highlighted manner. This is just what we are trying to say.
Suppose we search the term ‘Lorem Ipsum. Here is the result you get.
The above image shows the search term “Lorem Ipsum” in bold in the places where it occurs.
Importance of highlighting search terms.
When a person looks at the result, he may not quickly relate to it. By highlighting the search term, the presented result grabs the attention.
The objective is to draw attention to important information in a text. It is helpful because it first invites the reader to pick up the important parts and then review that information later.
Accordingly, To highlight search terms in the result, Follow the steps below:
- open search.php and look for the for code given below:
<?php the_title(); ?>
- Now, Replace the code with the below one:
<?php echo $title; ?>
- Note -you have to 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); ?>
- Then Open your CSS file.
- In your CSS file, add the styling for the class search excerpt then, the term will be highlighted.
- Presently the code is making the search terms bold. You can try the simple CSS in your theme’s stylesheet.
strong.search-excerpt { background-color:yellow; color:blue; }
This was the simple step you need to follow to highlight the search term. We hope this has helped you.
You can also check our another guide on how to display search term and result count in WordPress.