Ihave recently been working on a “LinkWords” plugin for WordPress. This idea comes from the e107 LinkWords plugin which allows the site admin to setup pairs of keywords and links that will automatically be inserted into news items, forum posts, etc.
So if you always find yourself turning every instance of the word “Amazon” into an affiliate link then it makes sense to have this done automatically!
Now there are several “Autolink WordPress plugins” floating around but none did quite what I wanted or they were commercial. I don’t like paying for stuff if I can help it and producing this kind of plugin is well within my skill level!
Preg_Replace excluding Tags
The toughest part of writing a plugin like this seems to finding a good regex pattern that will match the user’s entered keywords but will exclude all instances that occur inside HTML tags.
For example if you wanted to autolink the word class but didn’t want to break any HTML which includes a class reference you’d need to make sure only the correct instances of the word were updated.
The regex pattern I eventually settled on was as followes:
$regEx = ''(?!((<.*?)|(<a.*?)))(b'. $needle . 'b)(?!(([^<>]*?)>)|([^>]*?</a>))'si';
$output = preg_replace($regEx,$replacement,$haystack);
This pattern also conveniently excludes words that are caught between a tags. For example:
Here you don’t want the link to be automatically updated to a different link, so the pattern specifically excludes this case too.
It might also be nice to exclude words that are caught between other tags such as <code><quote> etc. If anyone has a good idea for that then please let me know! I guess we could keep building the pattern up to cater for all these cases?
This “linkwords” plugin will form part of my, as yet unreleased, collection of affiliate WordPress plugins that will one day be shared with the world.