How can I get the search terms highlighted without plugin?
Add these 2 functions to your functions.php
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;
}
Edit:
To use the_content for your search results use the function below:
function search_content_highlight() {
$content = get_the_content();
$keys = implode('|', explode(' ', get_search_query()));
$content = preg_replace('/(' . $keys .')/iu', '<strong class="search-highlight">\0</strong>', $content);
echo '<p>' . $content . '</p>';
}
In your loop or search.php file call <?php search_title_highlight(); ?>
instead of <?php the_title(); ?>
and use <?php search_excerpt_highlight(); ?>
instead of <?php the_excerpt(); ?>
In your css add the search-highlight class which will highlight all searched words in yellow.
.search-highlight {
background:#FFFF00
}