To properly highlight keywords in WordPress post titles, there are two feasible options: we can either use WordPress filters or jQuery. jQuery is surely the most performance-friendly solution, so we're going to use this one to accomplish our task. Let's see the details.
With jQuery, we need to create a regular expression to select only the keywords we're interested in. Then we can wrap these keywords with an HTML element:
var highlightKeyWords = function() { $('h1, h2', '#content').each(function() { var $header = $(this); var element = ($('a:first', $header).length) ? $('a:first', $header) : $header; var re = /(wordpress:?|php:?|css:?|html5:?|javascript:?|jquery:?)+/ig; var $html = element.html(); element.html($html.replace(re, '<strong class="keyword">$1</strong>')); }); };
The regular expression used above makes use of grouping patterns to properly match and replace one or more keywords. Notice that we're changing the HTML content of the target element. This element can either be a simple heading or an HTML link within an heading.