tags:

views:

27

answers:

2

Hi,

I am using built-in WordPress search.php routines, is it possible to highlight the word searched on, in context with the search results retrieved?

For example, if I typed in "products", any page that returned this matching word would be highlighted to the user.

Thanks.

A: 

Here is a function you can add to functions.php that will highlight the searched term in the results.

/* Search Highlighting ********************************************/
// This highlights search terms in both titles, excerpts and content

function search_excerpt_highlight() {
 $excerpt = get_the_excerpt();
 $keys = implode('|', explode(' ', get_search_query()));
 $excerpt = preg_replace('/(' . $keys .')/iu', '<strong class="search-highlight">\0</strong>', $excerpt);

 echo '<p>' . $excerpt . '</p>';
}


function search_title_highlight() {
 $title = get_the_title();
 $keys = implode('|', explode(' ', get_search_query()));
 $title = preg_replace('/(' . $keys .')/iu', '<strong class="search-highlight">\0</strong>', $title);

 echo $title;
}

To use this function it has to be added to your archive loop:

<?php if (is_search() ) { 

    search_excerpt_highlight(); } ?>
Chris_O
Hi @Chris_O - thanks for that but I can't seem to get it working. I added these functions in my function.php file and created a class "search-highlight" in my style.css file with a background-color of yellow but nothing happens. Do I need to call these functions from somewhere? Thanks.
tonsils
@tonsils I forgot to include how to add the function to your search loop. See edit above.
Chris_O