In this tutorial, we are going to see, how to highlight the searched keywords on the WordPress search result page. As you know theme’s search.php file is responsible for displaying all of the searched results for a specific search keyword.

To highlight the searched words, we will modify our search.php file a little bit. Open your ‘search.php’ file in any text editor, and you will get something like this loop

<?php if ( have_posts() ) :
while ( have_posts() ) : the_post()
    // Your code here 
    the_title();
    the_excerpt();
endwhile; else: endif; ?>

We are going to modify this title and excerpt a little bit. Please see the below:

<?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() ) ?> 

So now, we have two variables $title and $excerpt and we will use these two variables inside the above mentioned loop on our search.php file. See below:

<?php if ( have_posts() ) :
while ( have_posts() ) : the_post()
    // Your code here 
    echo $title;
    echo $excerpt;
endwhile; else: endif; ?>

After that, we are going to write some CSS to the class ‘search-instance’ on our style.css file. Sample CSS are given below:

span.search-instance {
    font-weight: bold;
    background: #f0e68c;
    padding: 2px;
    display: inline-block;
    text-transform: capitalize;
}

All done! Now try searching on the WordPress search box of your website and you will see your search term is highlighted on the WordPress search result page.

We hope this tutorial was helpful and easy for you. If you would like to read some more tutorials, you are welcome to visit our WordPress blog page.

Thank you.