Highlight Search Terms for WordPress

Very lightweight (vanilla) Javascript that wraps search terms in an HTML5 mark tag within WordPress search results.

Description

Highlights search terms within WordPress generated search results, both on the search results page and on each linked post page itself.

This plugin is light weight and has no options. It started as very simple fusion between How to Highlight Search Terms with jQuery – theme hack by Thaya Kareeson and Search Hilite by Ryan Boren. It has since evolved with many optimizations, HTML5 and bbPress support.

Since version 1.6 it no longer depends on the jQuery library.

Features

  • Click through highlights: Highlights not only on WP search results page but also one click deeper inside any of the found pages
  • Character and case insensitive (lenient) highlighting
  • BuddyPress / bbPress compatibility: highlighting within forum searches
  • Caching (WP Super Cache) compatibility
  • Search terms wrapped in double quotes now considered as single term

What does it do?

This low impact plugin finds all search terms on a search results page inside each post and highlights them with a <mark class="hilite term-N"> ... </mark> tag.
Note that N is a number starting with 0 for the first term used in the search phrase increasing 1 for each additional term used. Any part of a search phrase wrapped in quotes is considered as a single term.

What does it NOT do?

There are no CSS style rules set for highlighting. You are free to use any styling you wish but to make the highlights visible in browsers that do not support HTML5 like Internet Explorer 8 or older you absolutely need to define at least one rule.
Modern HTML5 browsers will use their own highlighting style by default, which usually is a yellow marker style background.

So what do I need to do?

In most cases, it should just work. But you can do two things to ensure backward browser and theme compatibility:

  1. Define CSS rules: There are no configuration options and there is no predefined highlight styling. You are completely free to define any CSS styling rules in your themes main stylesheet (style.css) or the Custom CSS tab if the WordPress theme customizer.
    You can find basic instructions and CSS examples in the FAQ’s.
  2. Check your theme: In most up to date themes (including WP’s own default theme) post and page content is shown inside a div with class hentry. This means search terms found in post and page content will be highlighted but not similar terms that accidentally show in the page header, sidebar or footer.
    If your current theme does not use the hentry class (yet), this plugin will look for IDs content, main and finally wrapper but if none of those are found, it will not work for you out of the box. See the last of the FAQ’s for ways to make it work.

Available hooks and filters

  1. hlst_query_vars – The array of WordPress query variables that the plugin will identify as a search query. Must return an array. Default: ['search_terms','bbp_search'] (WordPress abd bbPress search)
  2. hlst_input_get_args – An array of GET variables that the plugin will identify as a search query. Must return an array. Default: ['hilite'] (for click-through highlighting)
  3. hlst_selectors – The array of possible HTML DOM element identifiers that the script will try. The first viable identifier it finds elements of will be scanned for search terms to mark, the rest is ignored. So the order is important here! Start with the element closest to, but still containing all the post/page title, excerpt or content.
  4. hlst_events – The array of DOM event listeners that the inline script will watch for. Default: ['DOMContentLoaded','post-load'] (on Document Ready and for Jetpack Infinite Scroll and others).
  5. hlst_inline_script – The inline script that will be added to the plugin script file. Can be used to add to or alter the inline script. Must return a string.

Known issues & development

  1. If your theme does not wrap the main content section of your pages in a div with class “hentry” or HTML5 article tags, this plugin might not work well for you out of the box. However, you can make it work. See the last of the FAQ’s for an explanation.
  2. Josh pointed out a conflict with the ShareThis buttons plugin. Since then, that plugin has been completely rewriten so please let me know if the problem still exists. Thanks!
  3. When search engine referrer is using SSL (notice the https:// in the URL) then the search terms cannot be determined. Most search engines are always over SSL nowadays. There is no way to get around that issue.

Please file bug reports and code contributions as pull requests on GitHub.

Installation instructions

To make it work, you will need to take up to three steps, depending on your wishes and WordPress theme. (I) A normal installation and activation procedure; (II) Make sure your theme uses any of the recognized classes or ID’s for the post content div so that the script knows where and where not to look for search terms;
and (III) optionally add CSS styling rules to get highlighting for older browsers that do not support HTML5 like Internet Explorer 8 and below.

I. Install now or use the slick search and install feature (Plugins > Add New and search for “highlight search terms”) in your WP2.7+ admin section or follow these basic steps.

  1. Download archive and unpack.
  2. Upload (and overwrite) the /highlight-search-terms/ folder and its content to the /plugins/ folder.
  3. Activate plugin on the Plug-ins page

II. In most up to date themes (including WP’s own Default theme) post and page content is shown inside an ARTICLE element or DIV with class hentry.
This is recognized by the hilite script, which means search terms found in post and page content will be highlighted but not similar terms that coincidentally reside in the page header, menu, sidebar or footer.

If your current theme does not use these common designations (yet), this plugin will look for some other possible tags like #content, MAIN, #wrapper (which might include the header, sidebar and footer areas) and finally the BODY.

If this causes issues on your theme, see the last of the FAQ’s for ways to make it work.

III. Optionally add at least one new rule to your themes stylesheet or the Custom CSS editor to style highlightable text.

For example use .hilite { background:#D3E18A; } to get a moss green background on search terms found in the content section (not header, sidebar or footer; assuming your Theme uses a div with class “hentry”).

Please find more examples in the FAQ’s.

Frequently Asked Questions

I do not see any highlighting!

This plugin has no configuration options page and there is no predefined highlight styling. For any highlighting to become visible in browsers that do not support HTML5 like Internet Explorer 8 or older, you have to complete step III of the installation process.
Edit your themes stylesheet (style.css) or the WordPress theme customizer Custom CSS tab to contain a rule that will give you exactly the styling that fits your theme.

If that’s not the issue, then you might be experiencing a bug or plugin/theme conflict. Time to get some Support 🙂

I want to customize the highlighting but have no idea what to put in my stylesheet. Can you give me some examples?

Go in your WP admin section to Appearance > Customize > Custom CSS and add one of the examples below to get you started.

For a moss green background highlighting:

.hilite {
    background-color: #D3E18A;
}

Yellow background highlighting:

.hilite {
    background-color: yellow;
}

A light blue background with bold font:

.hilite {
    background-color: #9CD4FF;
    font-weight:bold;
}

Orange background with black font:

.hilite {
    background-color: #FFCA61;
    color: #000000;
}
Please give me more advanced CSS examples

If you want to give different terms used in a search phrase a different styling, use the class “term-N” where N is a number starting with 0, increasing 1 with each additional search term, to define your CSS rules.
The below example will make every instance of any term used in the query show up in bold text and a yellow background except for any instance of a second, third and fourth term which will have respectively a light green, light blue and orange background.

/* Default highlighting, but bold text. */
.hilite {
    background-color: yellow;
    font-weight: bold;
}
/* Moss green highlighting for second search term only. */
.term-1 {
    background-color: #D3E18A;
}
/* Light blue highlighting for third search term only. */
.term-2 {
    background-color: #9CD4FF;
}
/* Orange highlighting for fourth search term only. */ 
.term-3 {
    background-color:#FFCA61
}

Keep in mind that for the first search term the additional class “term-0” is used, not “term-1”!

Terms outside my post/page content get highlighted too

The script will search through your page source code for viable sections that usually contain page or post content, most commonly used in WordPress themes. Like ARTICLE or a DIV with class “hentry”. If that is not available, the script will look for other commonly used divs like #content, #main, #wrapper. However, in your particular theme, none of these divs might be available…

Let’s suppose your theme’s index.php or single.php has no <div <?php post_class() ?> ... > but wraps the post/page content in a <div id="someid" class="someclass"> ... </div>. This will not be recognized by the script as a post/page content container and the script will default to highlighting starting with the BODY element.

This will result in terms getting highlighted in the header, menu, sidebar and footer too.

You can do one of three things to solve this:

A. Change your theme templates like single.php, page.pho and search.php so the post/page content div has a class “hentry” (you can append it to existing classes with a space like class="someclass hentry").

B. Add a filter in your theme’s functions.php (or a seperate plugin file) like this:

add_filter(
    'hlst_selectors',
    function( $selectors ) {
        // custom theme selectors (change and append as needed)
        $my_selectors = array(
            'div.someclass'
        );
        return $my_selectors + (array) $selectors;
    }
);

C. Switch to a theme that does abide by the current WordPress conventions 🙂

78 Comments

I am trying to use your Highlight Search Terms WordPress plugin with the Atahualpa theme.

After I activate the plugin and perform a search, the first search results page entry is repeated 5 times and no others appear. Oh, and there is no highlighting either.

The search function works correctly again once I deactivate your plugin.

Suggestions?

You have hit on a problem. I see this happening with the default Twenty Ten theme too ( so it is not just the theme you are using ) but with some other themes there is no problem…

Here is a theme specific fix to get it working for now:
1. Open Plugins > Editor and select “Highlight Search Terms”
2. Find the line ( just below “// Get query variables”) where it says $area = '.hentry';
3. Change it to $area = '#middle';
4. Save

I Hope to get it fixed for others soon but until then, this should work 🙂

The fact that you see no highlighting is probably because you have not added any highlighting rules to your stylesheet. A simple rule like .hilite { background-color:yellow } should make the search terms pop out with a yellow marker-like background. More intricate rules to make different terms stand out with different styles, are suggested in the readme and on this page.

Well, found that for Atahualpa theme, you don’t have to use your plug-in for highlighting. Instead of adding a “.hilite” CSS style, use “.search-match” with a background color. The theme will then do highlighting automatically. Sorry to bother you.

That’s good to know. The theme apparently has a similar function baked in. Thanks for sharing 🙂

my category called “Paulinho da Viola” sound activated the plugin has highlighted all the words separately. Example: “Paulinho” all words, “da” all words and “Viola” all words. Want it highlighted the three together.

what to do?
thanks

Hello,
I have same the concern. I work with the topic represent. The first result is well highlighted, but not the others… Which can be the problem? Thank you for your answers. Cordially.

About that theme, in the header there is a block of scripts called that return 404:
<script type="text/javascript" src="js/prototype.js"></script>
<script type="text/javascript" src="js/scriptaculous.js?load=effects,builder"></script>
<script type="text/javascript" src="js/lightbox.js"></script>

But that is not the cause of the issue. It seems the prototype and jquery library are conflicting, resulting in the error

Uncaught exception: TypeError: ‘term.replace’ is not a function

on the second call (after the first successful call) to that same jquery function.

I have the impression it’s the lightbox 2 plugin that uses prototype. Try disabling it to see if that changes anything… If that helps, consider using another lightbox that uses jquery instead of prototype. Like FancyBox… got a plugin for that as well, you can find it on this website.

Right now, you are using two plugins that depend on jquery (hilite search terms and cforms) and one that depends on prototype. It makes no sense using (and thus loading on each page view) two different libraries when you can do with just one 🙂

Hi,

I love the plugin but it doesn’t seem to work witn non-Latin characters for some reason, Hebrew in this case. Search results are returned just fine but only keywords in English are highligted. Any ideas? 🙂

Thanks a lot,

Amir

Hi Amir, it sounds like a problem with javascript recognizing the non-latin characters. Do you have a link to your site for me? I’d like to see it live to learn more about the issue… Thanks 🙂

Hi Amir, the plugin itself cannot do that but you can make it happen by editing your theme… What the plugin needs is the s query parameter in the page request. Let’s say you searched on your site for the words “windows 7”, then the URL looks like http://www.amirdotan.com/blog/?s=windows+7 and it is the s=windows+7 that is used by the plugin to find the key words. Now on that search results page, the URLs for each post listed do not have that s= parameter anymore but if they would have, then the following page would have the search term highlighted as well. So the trick is to make your theme re-use the query parameters in the search results permalinks.

There are two ways to approach this:

1. Find the template that is used for the search results. It depends on your theme: it is usually called search.php but in TentyTen for example, you would need to create a new file called loop-search.php … Then instead of using the_permalink() you might try something like echo add_query_arg('s', get_search_query(), get_permalink($post->ID))

… or …

2. Edit your themes functions.php and add the following code

add_filter('the_permalink','add_my_search_query_to_permalink');

function add_my_search_query_to_permalink($url) {
if( is_search() )
return add_query_arg('s', get_search_query(), $url);
else
return $url;
}

Please note: these code snippets are untested so be prepared to revert to the original files to get your site back online 😉

Hello RavanH

I’ve installed 0.7 and it works…. however when I search for a term with quotes .. ie “Iran Oil” (so it gets all posts with ‘Iran Oil’ and not for eg ‘Iran has Oil’ in them)…. the search results terms are not highlighted. The highlight only works if I enter a search without quotes.

Any help appreciated.

Hi Zaahid, thanks for reporting this… It’s currently not programmed into this plugin to make the distinction between quoted and unquoted search strings but I’ll take it as a feature request for future development 😉

Hey RavanH,

The plugin is great. thanks for your work! Right now it highlights my search terms if they are at the beginning of a string, but I was wondering if there was a way to make it highlight if the search terms if they are in the middle or end of a word?

For example:
-If I search “Word” and a result is “WordPress”, I get the proper highlighting WordPress.
-If I search “Press” and the result is “WordPress”, I get no highlighting.

Am I doing something wrong?

Hi RavanH,
Is there a way to highlight accented words?
My website is in spanish and I need to hightlight the search term with or without accented characters. e.g. caida = caída.
Can you point into the right direction, I don’t have too much knowledge with jQuery.
Thanks!
Martin.

Hi Martin, words with accented characters should be recognised by the plugin already. Search for “donné” on this site for example… Or is that not what you mean?

Hi RavanH,

this plugin is only used on the search page. Wouldn’t it be better to change some code, that the Javascript is only included in the search page?

if(is_search()) {

echo ‘

var hlst_query = new Array(‘ . implode(‘,’,$filtered) . ‘);
var hlst_areas = new Array(“‘ . implode(‘”,”‘,self::$areas) . ‘”);

‘;
} else {
echo ”;
}

Hi Patrick, the plugin is not only active on the search page. It will also highlight search terms (1) on incoming traffic from search engines (as long as those where not logged in to Google because then the used search terms are blocked and cannot be detected by the plugin) and (2) when you click one of the internal search results, the terms will be highlighted on that next page… Those cases will not fall under is_search().

But you are right, the script is included even when it is not needed. This is done for two reasons. The script is fairly lightweight and I figure that the downside of running extra PHP routines to detect if the script is needed (like I said, not only is_search() will do it) will hardly make up for simply including it each time. Another reason is cache plugin compatibility. Like WP Super Cache running on this website. To do this, I have moved a large part of the search term detection from the WP internals to the javascript itself and so, inclusion on every page is needed.

Former versions of the plugin worked differently and did not include the script when it deemed not necessary but this meant incompatibility with caching plugins. In the next version, I plan to separate the main script in two parts where detection is always included which then does a writeline to include the second part if it does indeed detect search terms.

Hope that explains it a bit 🙂

Hi Bart, thanks for reporting this. I’ll have a look into it and find a way to repeat the issue…

Ok. Thanks.

If you want i can activate the plug-in for a few minutes but not to long. Send me a mail to say when.

W3 total cach issue

My site is avelim.co.il

It runs on Hebrew wordpress 3.5.1 with the theme Weaver II Pro 1.3

When you search for a term in the search box widget it highlights the searched term in the search results. This works very well when W3 total cach is deactivated. It does not work when W3 in active.

How can I fix this?

Hi Yoram,

Doing a search on your site now, I see highlighting. And it looks like you are running W3TC… Is it a specific option in W3TC that breaks search highlighting?

Checked your site in Chrome, Firefox and Opera (don’t have IE, sorry) but see no problem…

Hi,

I have installed the plugin in my custom theme. The search.php displays the search results correctly highlighted, but immediately the page disappears (goes blank). It seems to be attempting to connect to something. I have attempted the solutions described in the FAQ page but no luck so far.

Thanks.

here is the search form (I have disabled the plugin for now)
http://pathofshe.com/blog/

Hi Levi, it looks like you disabled the highlight plugin but the issue sounds like a javascript conflict. First of all, you need to make sure the search results page source code starts with the DOCTYPE declaration which in your case, it does not. Then make sure the jQuery library is only loaded once, which again, it appears not to be the case (Twitter/jquery.js)… Next, you’ll need to eliminate conflicts with other plugin scripts by disabling them all and finally eliminate a conflict with the themes scripts or source code errors by switching to the default theme.

Thanks for taking the time to look at my problem. I have corrected the doctype and jQuery issues. The highlight search plugin is now active, would you be able to take one more look at http://pathofshe.com/blog/? The conflict is probably with Jetpack, although I notice that when the program hangs it seems to be attempting to “read s.gravatar”.

Your plugin is neat and I would like to get it to work but for me it’s more of a ‘nice to have’ rather than ‘need to have’. The Jetpack functions are more important to me. Switching to a default theme is not an option.

Thanks again!

Hi Levi, it’s a weird issue. The error occurs indeed in the WordPress.com stats script but after activating the stats module on my own site (this one) effectively running the two plugins together like on your site, the error does not occur. I have the feeling it’s related to something else but cannot pinpoint the source of the problem.

Could you try disabling all other Jetpack modules except Stats? If that does not solve it, then it might be related to the Typekit library that seems to be loaded by your theme…

Hi RavanH,

I tried disabling everything in Jetpack other than the stats but the problem persists. Same with typekit.

The problem definitely is Jetpack – the problem occurred on my other site levimust.com but resolved when I disabled Jetpack entirely. I will continue to try modifying the Jetpack setup and see if the conflict resolves. I’ll let you know if it is resolved.

Once again, thanks for your time. It is a really nice plugin.

Very odd. Like I said, Jetpack and the Stats module are running alongside Hilite Search Terms on this very site without any issues… You said “Same with typekit.” Did you mean you removed that from the theme? Are there no other (font) scripts depending on Typekit that start failing then? Last thought: could you change the Stats module setting called “Hide the stats smiley face image.” to see if that changes anything?

I removed these files form my header.php, thus removing everything typekit:

try{Typekit.load();}catch(e){}

Also, tried disabling the smiley face..problem persists.

It is definitely related to Jetpack since when I deactivated Jetpack entirely Hilight Search worked fine. But I wonder if there is any significance to the fact that when the screen goes blank, the last thing happening is it is attempting to read my gravatar…I wonder if the connection to https://en.gravatar.com/?

It might be related but I’ve got Gravatar Hovercards running too without issues… Can you try disabling the Gravatar Hovercards module?

I tried removing the gravatar from gravatar.com but it had no effect on the problem. Is there a different way to disable the Gravatar Hovercards module?

The plugin seems to be working ok on my other site at levimust.com

Thanks.

Hi Levi, go to the Jetpack admin page (where all the modules are listed) and find the Gravatar Hovercards module with the two buttons Learn More and Configure. Now click on Learn More and the button that said Configure before will now show Deactivate… Or you can go to Settings > Discussion and deactivate the Avatar and Gravatar Hovercards options there to see either one changes to the issue 🙂

Nope…disabled the Gravatar, and for luck also tried disabling the smiley face again. The page still hangs, only it isn’t stopped at the reading Gravatar step any more….curious!

Hi Levi, looking at the source code of a search result page, I notice that it has TWO html tags (line 2 and 3) while there can only be one… Plus the div with id “head_image_container” does not seem closed. You’ll need to fix these errors because the DOM tree is messed up.

But I’ve also found that when you edit my plugin like below, it should work in spite of the problems with the DOM tree…

Open the plugin file hlst.php in the WordPress plugin editor and find the part (near the top) that reads


static $areas = array( // Change or extend this to match themes content div ID or classes.
'div.hentry', // The hilite script will test div ids/classes and use the first one it
'#content', // finds so put the most common one first, then follow with the less
'#main', // used or common outer wrapper div ids.
'div.content', // When referencing an *ID name*, just be sure to begin with a '#'.
'#middle', // When referencing a *class name*, try to put the tag in front,
'#container', // followed by a '.' and then the class name to *improve script speed*.
'#wrapper' // Example: div.hentry instead of just .hentry
); // Using the tag 'body' is known to cause conflicts.

Now change that to

static $areas = array(
'article'
);

Your change to hlst.php fixed the issue!

I removed the extra tag, but the problem persisted. I don’t think the “head_image_container” tag was not closed, as far as I can see. Perhaps there is another open tag but I can’t see where.

Once again, thanks so much for your patient sleuthing. I really like your plugin.

Levi

Hey I like your plugin really nice.
There is a flaw in the setup you are using; try to search for the letter ‘e’. This will highlight the results nice. Then navigate to any page (or even the homepage) of your wordpress blog. The letter e is still highlighted. I think this is because of your latest update.

Is there a way to turn this off?

Hi Dirk, this is done to keep highlighting when a visitor does a search and then clicks on one of the search results. The term is then highlighted again. At this point there is no way to turn this off but I’ll consider a way to either be able to turn it off or to only do click-through highlighting when actually clicking a search result and not when navigating to any random page…

Hey RavanH, the last option sounds best from a user perspective. I like the fact that the search term is highlighted when I search on the site but going to a different page and still have the term highlighted is a bit strange in my opinion.

So 1 vote for the last option you mention 🙂

I LOVE the functionality but when I activate the plugin and use search, my pages load fine. However, my posts will not. Any ideas?

I figured out the solution. I didn’t have the proper tags. I experimented with adding one but it didn’t work, until I changed the order and added my own up the list. Then it worked. I added a #post_content. Thanks!

Hi, love the plugin (as do my clients) but was wondering if there was any way of only finding/highlighting whole words. For example, when I did a search on a dev site for “the stripey street cat” it highlighted the ‘the’ in words like ‘there’, ‘altogether’ and ‘further’ along with the whole words in the search query. Any options? Many thanks, Ellen.

A very belated thank you for getting back to me – I appreciate it. The current version of the plugin is all good – and I’m quite happy to leave things as they are if there’s incompatibilities that may cause problems! Thanks again, Ellen.

I am using Relevanssi search, Genesis and Dynamik Website Builder. When I put in the search terms: talk it up, every word that has any of those terms as part of it gets highlighted. I believe that is called a “fuzzy” search. I don’t want that. I set my Relevanssi to the “and” as the default operator. Can’t I somehow set your plugin to use the same operator? I tried putting the search string in quotes, but that didn’t work.

Hi Kevin, the plugin uses “fuzzy” search because the internal WordPress search does too. You want that disabled but my plugin does not have any options yet. They will come one day but not tomorrow…

Is there any way for me to disable the fuzzy search though coding? if not, do you know of any other highlighting plugins that make this possible? I like your plugin, but my client is not happy with the fuzzy search. I have to change it.

Hi Kevin, I can send you a development version that has does a strict search when quotes are used in a regular WordPress search. If you can test that in combination with Relevanssi, I would appreciate it much 🙂

Thanks for this plugin is just what I needed. I have a problem with Google Custom Search CSE integrated on my website, the plugin seems to not work. If I use the search for WordPress I have no problem with CSE looks just don’t go.

Thank you
Vito

Hi Vito, the plugin can only work with WordPress normal search pages. I have no idea how Google Custom Search works or how to make the two plugins work together. Sorry.

We used this plugin to highlight the search terms. The query results are highlighted for the document title and excerpt. The search terms within the body of the text are not highlighted. How can this be accomplished with this WP plugin? or is there an alternate plugin you are aware of? If the plugin returns a result set for display and highlighting; could it be invoked again within the plugin just for the text body for the query results? Thanks in advance.

Hi Ray, search term highlights should appear in the body text as well as title and excerpts. And doing a search for “knowing” on your site, I see it highlighted both in title/excerpt as well as in the page content after clicking the first result. Or is this not what you are asking?

That is what I am asking for but it is not highlighting within the document body when I run it. We are using WP and Elementor. Perhaps you could take a screen shot of your results and send to me?

Try with an anonymous browser window, or logged out from your WP admin. It might be caused by a conflict with something that is added (or different) for connected users…

ok I tried the Epic anonymous browser and get the same result. Is there a way to hire you may the highlight happen within each search result document body by enhancing your plugin? I am at a loss here. Love the plugin just need to take it 1 step further. I’ve tried the Chrome, IE11 and Epic and get the same result of no highlighting of the document text within the document on the key word search. Any help or suggestions are greatly appreciated.

OK, I see the problem: I used a regular WordPress search like this https://bigmacspeaks.life/?s=knowing and then it works fine but not when using the search field there in the header. It does not look like a regular WordPress search form. Is it a search plugin or something integrated in your theme?

Leave a Reply to Mike Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.