Highlighting Word (s) Search in WordPress Search

I use the built-in WordPress search.php routines, is it possible to highlight the search word in the context of search results?

For example, if I typed β€œproducts,” any page that returned that matching word would be highlighted to the user.

Thanks.

+4
source share
2 answers

Here is a function that you can add to functions.php that will highlight the search term in the results.

/* Search Highlighting ********************************************/ // This highlights search terms in both titles, excerpts and content function search_excerpt_highlight() { $excerpt = get_the_excerpt(); $keys = implode('|', explode(' ', get_search_query())); $excerpt = preg_replace('/(' . $keys .')/iu', '<strong class="search-highlight">\0</strong>', $excerpt); echo '<p>' . $excerpt . '</p>'; } function search_title_highlight() { $title = get_the_title(); $keys = implode('|', explode(' ', get_search_query())); $title = preg_replace('/(' . $keys .')/iu', '<strong class="search-highlight">\0</strong>', $title); echo $title; } 

To use this function, it must be added to your archive loop:

 <?php if (is_search() ) { search_excerpt_highlight(); } ?> 
+3
source

All Articles