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="https://wordpress.stackexchange.com/questions/274268/<?php the_permalink(); ?>">
<h3 class="title-heading"><?php the_title(); ?></h3>
</a>
<?php
$searchresults = $post->post_content;
$highlightword = get_search_query();
$searchresults = str_replace($highlightword,
'<span style="background-color:#ffff00;">'.$highlightword.'</span>',
$searchresults);
echo $searchresults;
endwhile;
else: echo "No matching result found";
endif;
?>
</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.