For my WordPress Search results page, I have added highlighting to show where search term appears on the results page. But the replacement code changes the text of the page to the case that was used in the search term.
For example:
Search Term: remote Employee ENGAGE
Text on Page before highlight: Remote employee engagement
Resulting text after highlight replacement: remote Employee ENGAGEment
Desired text after highlight replacement: Remote employee engagement
Here is the code I used in my content-search.php
<?php $title = str_ireplace( $s, '<span class="search-instance">'.$s.'</span>', get_the_title() ) ?>
<?php $excerpt = str_ireplace( $s, '<span class="search-instance">'.$s.'</span>', get_the_excerpt() ) ?>
<?php echo $title; ?>
<?php echo $excerpt; ?>
And the css to highlight the text:
span.search-instance {
font-weight: bold;
background: #fffdca;
padding: 2px;
}
Can someone offer some suggestions on how to get the highlighting done, with a case-insensitive search, but also without changing the case of the text on the page during the highlighting process.
Cheers,
SunnyOz
UPDATE:
I don’t think I can do what I want with str_ireplace
.
I think I will probably need to use something like preg_replace
with some regex
that also allows partial matches (ie: Don’t limit to match a word boundary)- but I don’t know how to set that up in my code example.
If it is true that I need to use preg_replace
instead of str_ireplace
, I could still use some help.
How can you do a case-insensitive search of the get_the_title()
and get_the_excerpt()
separately with the search term used – using preg_replace
?
2
Answers
I did find a way to do what I wanted. I found the solution from this page: https://www.wpbeginner.com/wp-tutorials/how-to-highlight-the-search-terms-in-results-in-wordpress/
Here is the new code I changed: