Highlighting the keywords in search results within the post title and excerpt will let your users know what they’ll find in the article.
Instructions: Add to the following code to the functions.php of your WordPress theme.
function wps_highlight_results($text){ if(is_search()){ $sr = get_query_var('s'); $keys = explode(" ",$sr); $text = preg_replace('/('.implode('|', $keys) .')/iu', '<strong class="search-excerpt">'.$sr.'</strong>', $text); } return $text; } add_filter('the_excerpt', 'wps_highlight_results'); add_filter('the_title', 'wps_highlight_results');
You may also enjoy replacing keywords in the_content and the_excerpt.
hi, hope this finds you weel, thanks for the coding!
i’m a portuguese speaker and i need the search to match the accents as weel(:
for ex: if i search ‘mae’, it doesn’t hightlight the result, as in the text it shows ‘mãe’.
how can i surpass this accent issua,please?
thanks,
kind regards
Found issue with this function, if you search for a term that is exactly the same as a navigation menu item it messes the navigation, duplicates the key words inside the menu item along with couple of other issues.
Any way of getting around this?
Thank you
Sibbo
It may be conflicting with the theme. You may have to edit how the style is applied.
it works like a charm. thank you
Good to know!
it works a magic…. muito obrigado.
it messes up links that contain the search terms
i have a function that limit my excerpt , how can i do that with it ?
Thank you very much for this snippet. I have found a small issue with it though — it de-capitalizes the search term in the search results.
For example, if I have a post titled “Include password protected posts” and then search for “include”, the title of my post in the search results will be displayed as “include password protected posts”.
Any idea how this could be fixed?
Change the replacement string from
''.$sr.''
to
'$1'
Hi,
I’m not fully deep into PHP coding so when I replaced the strings, I got errors.
My site almost went down.
You may want to check out this page: https://www.isitwp.com/properly-add-code-snippets-wordpress-site/
Did you see any error messages? If so, what were the messages?