If a user utilizes the WordPress search function to scour your site for something, then you know that their query is probably pretty specific. You can make it easier on your visitors by highlighting search terms in their search results. This way, they'll be able to immediately scan to the appropriate places in your content.
First, open or create your theme's functions.php
file. You'll be creating a custom filter that latches onto post content and excerpts, and the functions.php
file is the correct place to do so. Insert the following code in this file:
<?php function highlight_search_terms($content) { if( is_search() ) { $search_term = get_query_var('s'); $content = preg_replace( "/\b($search_term)\b/i", '<span class="search-result">$1</span>', $content ); } return $content; } add_action( 'the_content', 'highlight_search_terms' ); add_action( 'the_excerpt', 'highlight_search_terms' ); ?>
Open your theme's stylesheet...