Highlight the Search Terms in WordPress Search Results
March 18, 2009 · Print This Article
When you search on Google or any other major search engine, the words you searched for are highlighted in the results to make it easier for you to scan.
We can do the same with your wordpress search results page.
In your search.php, search for the following:
<?php the_title ();?>
This is the code for showing the title of each of the results.
In the default theme, it will be wrapped up in a line like this:
<h3 id="post-<?php the_ID(); ?>">
<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>">
<?php the_title(); ?></a>
Now, replace the <?php the_title(); ?> part with:
<?php echo $title; ?>
Finally, before this line, paste the following:
$title = get_the_title();
$keys= explode(" ",$s);
$title = preg_replace('/('.implode('|', $keys) .')/iu', '<strong class="search-excerpt">\0</strong>', $title);
Your search terms will now be wrapped in tags. Bolding works great for this, but if your headline is already in bold (or h1 etc. tag) then use CSS to style it in some other way for emphasis.