Tell me more ×
WordPress Answers is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

How can I get the search terms highlighted without plugin?

share|improve this question

1 Answer

Add these 2 functions to your functions.php

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;
}

Edit:

To use the_content for your search results use the function below:

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

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

In your loop or search.php file call <?php search_title_highlight(); ?> instead of <?php the_title(); ?> and use <?php search_excerpt_highlight(); ?> instead of <?php the_excerpt(); ?>

In your css add the search-highlight class which will highlight all searched words in yellow.

.search-highlight {
    background:#FFFF00  
    }
share|improve this answer
3  
Apply preg_quote() to $keys to prevent your regex from blowing up in case of special characters like parentheses or brackets. – Geert May 1 '11 at 7:09
1  
What about highlighting the search term after the user clicks on the single and goes inside the post? Then the get_search_query() returns an empty string – Maor Barazany May 22 '11 at 23:47
1  
Those should be filters for the_excerpt and the_content instead. Anyway: Nice answer, but the comment from @Geert could be worked in :) – kaiser Oct 13 '12 at 0:25
It apply <strong class="search-highlight"> code in our readmore link also if it have search term, How can we solve that. – user22614 Oct 18 '12 at 7:20

protected by toscho Oct 29 '12 at 11:22

This question is protected to prevent "thanks!", "me too!", or spam answers by new users. To answer it, you must have earned at least 10 reputation on this site.

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