This PHP hack for WordPress enables you to highlight keywords in the search results of your WordPress site. We will use jQuery, a language built natively inside of WordPress.
Adding a PHP command in functions.php
From the Theme Editor, open the file called functions.php or open by your favorite FTP client by locating it in the directory / wp-content/themes/Your-Theme /
Using an FTP client can perform a backup prior to editing the file directly which allows you to undo a wrong manipulation.
---
Then paste the following lines of code to the file if you use the theme Twenty Ten (default):
1 2 3 4 5 6 7 8 9 10 11 12 | hls_set_query function () { $ Query = attribute_escape (get_search_query ());if (strlen ($ query)> 0) { echo ' <script type="text/javascript"> hls_query var = "'. $ query."; </ Script> '; } }hls_init_jquery function () { wp_enqueue_script ('jquery'); }add_action ('init', 'hls_init_jquery'); add_action ('wp_print_scripts', 'hls_set_query'); |
For other themes, it is often necessary to include these tags PHP according to this model:
1 2 3 | <php INSERT CODE HERE //Uncomment and do not use this Line break //?> |
Remember to Update the file to save the changes.
Editing file header.php
Also in the theme editor, open the header . php file that corresponds to the header of your site.
Paste the code lines below just before the tag we just look for:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <style type="text/css" media="screen"> .hls {background: # D3E18A;} </ Style> <script type="text/javascript"> jQuery.fn.extend ({ highlight: function (search, insensitive, hls_class) { var regex = new RegExp ("(<[^>]*>)|( b "+ search.replace (/([-.*+?^${}()|[ ] / ] ) / g, " $ 1") +")", insensitive? "ig", "g"); return this.html (this.html (). replace (regex, function (a, b, c) { return (a.charAt (0) == "<")? a: "<strong class=""+ hls_class +"">" + c + "</ strong>"; })); } }); jQuery (document). ready (function ($) { if (typeof (hls_query)! = 'undefined') { $ ("#post-1"). Highlight (hls_query, 1, "HLS"); } }); </ Script> |
Adjustments required customized color
To make this snippet working, you must specify the class or ID of the tag that will display the search results.
Twenty To Ten, it is #post-1 as indicated in this line of code:
1 | $ ("#post-1"). Highlight (hls_query, 1, "HLS"); |
We recommend using the Firebug extension for Mozilla Firefox which allows you to quickly identify the tag in question – also possible via the display of the source code of the page in the browser of your choice.
To change the highlight color, change the hexadecimal value for the following line:
1 | .hls { background: #D3E18A; } |
This value can be obtained easily via any photo editor or as a Firefox extension ColorZilla.
The search module integrated basic WordPress offers no visual identification of search terms in the search results page. The technique presented here will fill this gap unless you’d prefer to integrate the Google search engine to your site !
