Highlight searched keywords on WordPress search results page

Highlight searched keywords on WordPress search results page

In this tutorial, we are going to see, how to highlight the searched keywords on 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

<? 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:

<? $title = str_ireplace( $s, '<span class="search-instance">'.$s.'</span>', get_the_title() ) ?>
<? $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:

<? 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 WordPress search box of your theme and will get the highlighted searched word on your search page results 🙂

Thank you.