Shortcode for encoded email address
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:dude@example.com">
dude@example.com
</a>
Notice we include a CSS class for the email link in case we want to add some styles.