I want to trim my search results page down to 20 words before and 20 words after the highlighted search word. I am getting accurate search results and the search word is highlighting. I have tried variations with wp_trim_words(); such as:

            $trimmed_content = wp_trim_words( $searchresults, 25, NULL );
              echo $trimmed_content;

but what I so far cannot get and what I want is a search result that trims 20 words before and after the highlighted search word. My 'search.php' page code is:

    <div class="searchresultsbox"> 
    <?php if(have_posts()):while (have_posts()):the_post();?>
    <a href="<?php the_permalink(); ?>">
    <h3 class="title-heading"><?php the_title(); ?></h3>         
      $searchresults = $post->post_content;
      $highlightword = get_search_query();
      $searchresults = str_replace($highlightword, 
      '<span style="background-color:#ffff00;">'.$highlightword.'</span>',

      echo $searchresults;

      else: echo "No matching result found";
      </div><!-- /searchresultsbox -->
    </div><!-- /collcelltwo -->
  </div><!-- /tb-one-row --> 
</div><!-- /tb-one -->

Many thanks to Rick Hellewell for the "str_replace" function which highlights the search word. Thank you for the help.

  • i'm looking for exactly for the same thing, could not found anything, now writing custom function, let me know if you got any solution? i'll soon share my solution on this post.
    – Nestsouls
    Sep 26, 2017 at 18:43
  • @Nestsouls hi, I know the question is old. But is it possible to have your solution please ?
    – Jandon
    Oct 6, 2020 at 8:47

1 Answer 1


A random thought: put the search string into an array ( with explode). Find the array position of the highlighted string. Count back xx for the start, and forward xx for the end. Extract those array values, then implode them back into a string.

That would work for one searchresult word in the string. You'd have to loop through multiple occurrences of the searchresult word.

Say the full search result has 200 words. The searchresult word is at position 50. Extract words starting at 30 and ending at 70. Put the words back into one string. Show the string.

Might be a better way, though, but that was my first thought.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.