Is there a way we can set up the highlight functionality to only highlight the words on the page if it matches the exact sentence?
If I try searching for "how do i insure a house", the search results look funky and the highlight functionality spaces out the words.
Output:
This is my code:
function highlight_search_term_placeholders() {
static $iter = 0;
$ret = "|##{$iter}##|";
$iter++;
return $ret;
}
function highlight_search_term_cb() {
static $iter = 0;
$ret = "##{$iter}##";
$iter++;
return $ret;
}
function highlight_search_term($text){
if(is_search() && !is_admin()){
$keys = implode('|', explode(' ', get_search_query()));
$pattern = '/<[^>].*?>/i';
preg_match_all($pattern,$text,$matches);
$placeholders = array();
foreach ($matches[0] as $v) {
$placeholders[] = highlight_search_term_placeholders();
}
$text = preg_replace_callback($pattern,'highlight_search_term_cb',$text);
$pattern2 = '/(' . $keys .')/iu';
$text = preg_replace($pattern2, ' <span class="search-term">\1</span> ', $text);
$text = preg_replace($placeholders,$matches[0],$text);
}
return $text;
}
add_filter('the_excerpt', 'highlight_search_term');
function highlight_results_css() {
?>
<style>
.search-term { background-color:#FF0; }
</style>
<?php
}
add_action('wp_head','highlight_results_css');