Shortcode E-Mail Obfuscator

31.03.2024

Picture of a beautifully tidy garden

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)

See also

No contributions found