WordPress Code Snippets

A fresh mix of code snippets and tutorials

Shortcode for encoded email address

52

One way to help reduce spam is to encode your email address whenever displaying publicly. Here is a function that will do just that: display an encoded version of whatever email address you specify.

To do this, we’ll create a shortcode by placing the following code in our theme’s functions.php file:

function encode_email_shortcode($atts, $content = null) {
	for ($i = 0; $i < strlen($content); $i++) $encodedmail .= "&#" . ord($content[$i]) . ';';
	return '<a class="encoded-email" href="mailto:' . $encodedmail . '">' . $encodedmail . '</a>';
}
add_shortcode('email', 'encode_email_shortcode');

In the add_shortcode() tag, we’ve specified “email” as our shortcode, so to display an encoded email address in any post or page, do this:

[email]dude@example.com[/email]

This will display a regular email link to “dude@example.com”, but in the markup the email address will be encoded, like this:

<a class="encoded-email" href="mailto:&#100;&#117;&#100;&#101;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;">
	&#100;&#117;&#100;&#101;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;
</a>

Notice we include a CSS class for the email link in case we want to add some styles.

Learn more

WordPress Themes In Depth


Show Support

Like our new Facebook Page to show support!