Pluginless spam protection for WordPress

This short snippet will protect your and your clients’ input from e-mail address harvesters and spam attacks.

Why do you need this?

Amongst the many other baddies out there on the internet live email harvesters. E-mail harvesters are bots that make it their mission to read page after page on the internet in search of e-mail addresses. Those e-mail addresses usually end up on a list sold to advertisers or spammers.

We recently received a complaint from one of our clients about an overwhelming amount of spam. I knew immediately that the above-mentioned internet candy store robbers were involved.

Fool those fools!

I’m not a fan of the typical johndoe(at)mail.com solution for two reasons: it’s ugly and it’s not clickable, making for a poor user experience. Luckily, there’s a code-based solution, which means you can avoid adding another plugin.

WordPress has its own built-in function to prevent e-mail harvesting. It simply converts e-mail addresses into HTML entities, so e-mail harvesters no longer recognize them as e-mail addresses.

Paste the snippet below in your functions.php file in your theme directory. It will look for e-mail addresses in WordPress content editors and text widgets using Regular Expression and run the antispambot() function on them.


/**
* Secure e-mail addresses in content editors
*/
function secure_email_addresses($content) {
    $pattern = '/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})/i';
    $fix = preg_replace_callback($pattern, "antispam_pattern", $content);

    return $fix;
}
function antispam_pattern($result) {
    return antispambot($result[1]);
}
add_filter( 'the_content', 'secure_email_addresses', 20 );
add_filter( 'widget_text', 'secure_email_addresses', 20 );

I hope this helps a few of you out there to enjoy a life free of spam. Contact me if you have any problems implementing this solution.