Shortcode E-Mail Obfuscator

Table of contents

The following shortcode snippet is useful for disguising emails to protect them from SPAM. Please note that this method only works if Javascript is activated. Furthermore, there is no 1001TP4-proof protection against bots that collect email addresses from websites.

add_shortcode( mnc_mail', function ( $atts ) {

	$atts = shortcode_atts( [ 'email' => '' ], $atts, mnc_mail' );

	$calc_mail = function ( $text ) {
		$encoded_text = '';
		$length = mb_strlen($text, UTF-8');
		for ($i = 0; $i < $length; $i++) {
			$char = mb_substr($text, $i, 1, UTF-8');
			$encoded_text .= '\\u' . sprintf("x", ord($char));
		}
		return $encoded_text;
	};
	$obfuscate = $calc_mail($atts['email']);

	return <<< FORMAT
<a href="javascript:location='mailto:$obfuscate';void 0"><script type="text/javascript">document.write($obfuscate')
FORMAT;
} );Code language: PHP (php)