Home / excerpt / Highlight keywords in search results within the_excerpt and the_title
  • How to Highlight keywords in search results within the_excerpt and the_title


    I whipped up this little snippet that you can add to the functions.php of your wordpress theme to highlight keywords in search results for the_excerpt and the_title. A few highlight search results snippets floating around including a great one by Michael Martin. However they require you edit template files so this is my take on Michaels Idea.

    ( click code to copy )

    wordpress snippet : PHP

    function wps_highlight_results($text){
         $sr = get_query_var('s');
         $keys = explode(" ",$sr);
         $text = preg_replace('/('.implode('|', $keys) .')/iu', '<strong class="search-excerpt">'.$sr.'</strong>', $text);
         return $text;
    add_filter('the_excerpt', 'wps_highlight_results');
    add_filter('the_title', 'wps_highlight_results');

    ( WordPress codex functions, hooks, in this snippet. )

    the_excerpt, the_title, query, add_filter, _e, _ex, is_search, get_query_var, wp,
  • storetext

    Thank you very much for this snippet. I have found a small issue with it though — it de-capitalizes the search term in the search results.

    For example, if I have a post titled “Include password protected posts” and then search for “include”, the title of my post in the search results will be displayed as “include password protected posts”.

    Any idea how this could be fixed?

  • Ahmed Badran

    i have a function that limit my excerpt , how can i do that with it ?

  • JS

    it messes up links that contain the search terms