Automatically hide email addresses from spambots in WordPress

Lacey Tech Solutions are pleased to have been given the award for Best Website Development & SEO Agency 2019!

There may be times where you need to publically display your email address in parts of your website. If you show your email address on a page in your website you run the risk of a spambot crawling your website and adding your email address to a spam list. The result will be either a daily or weekly barrage of spam emails delivered to your email inbox.

This block of code will protect email addresses that are shown within your WordPress pages/posts and widgets areas – simply add the code below to your WordPress functions.php file.

function remove_plaintext_email($emailAddress) {
$emailRegEx = '/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4})/i';
return preg_replace_callback($emailRegEx, "encodeEmail", $emailAddress);
}

function encodeEmail($result) {
return antispambot($result[1]);
}
add_filter( 'the_content', 'remove_plaintext_email', 20 );
add_filter( 'widget_text', 'remove_plaintext_email', 20 );

What are WordPress Filters?

Filters are functions that WordPress passes data through. They are primarily responsible for intercepting, managing, and returning data before rendering it to the browser or saving data from the browser to the database. More information on the add_filter WordPress function can be found on the wordpress.org codex: http://codex.wordpress.org/Function_Reference/add_filter

In our case we want to search the content of our pages/posts for email addresses and apply the WordPress antispambot function before the content is shown in the browser.

What does the WordPress antispambot function do?

The WordPress antispambot function takes an email address and converts the characters to encoded HTML characters.

Web browsers will read the encoded HTML and show the email address to visitors but spambots would be unable to see the email address on the page.

How can I protect my email address inside my theme files?

If you need to add an email address to one of your theme’s files and you want to protect it from spambots then you need to call the encodeEmail function we created earlier.

<?php echo encodeEmail('hello@domain.com'); ?>

This article has a discussion on wordpress.stackoverflow.com Read Stackoverflow Discussion.

Ben Lacey is the Managing Director of Lacey Tech Solutions. He is passionate about everything to do with websites from design and development through to search optimisation and hosting. He started the company blog as a platform to help educate current and prospective customers about the ever changing website development industry.

What are your thoughts?

We hope you found our article useful and look forward to answering your questions.