Skip to content

Instantly share code, notes, and snippets.

@ihorduchenko
Created September 12, 2017 13:03
Show Gist options
  • Save ihorduchenko/87bbad97f1c194d9e02e1f0cb081d4bf to your computer and use it in GitHub Desktop.
Save ihorduchenko/87bbad97f1c194d9e02e1f0cb081d4bf to your computer and use it in GitHub Desktop.
Highlight search results in Wordpress search
function highlight_results($text){
if(is_search()){
$keys = implode('|', explode(' ', get_search_query()));
$text = preg_replace('/(' . $keys .')/iu', '<span class="search-highlight">\0</span>', $text);
}
return $text;
}
add_filter('the_content', 'highlight_results');
add_filter('the_excerpt', 'highlight_results');
add_filter('the_title', 'highlight_results');
add_filter('the_permalink', 'highlight_results');
function highlight_results_css() {
?>
<style>
.search-highlight { background-color: rgba(255, 255, 0, 0.6); color: #222b44; font-weight:bold; }
</style>
<?php
}
add_action('wp_head','highlight_results_css');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment