daniel-w
7/6/2016 - 5:18 PM

Function and shortcode to encrypt email addresses.

Function and shortcode to encrypt email addresses.

/**
 * Encrypt Email address
 */
function hide_email( $email, $text ) {
	if ($text == "") { $text = '"+d+"'; }
	$character_set = '+-.0123456789@ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
	$key = str_shuffle( $character_set ); $cipher_text = ''; $id = 'e' . rand( 1, 999999999 );
	for ( $i = 0; $i < strlen( $email ); $i += 1 ) { $cipher_text .= $key[ strpos( $character_set, $email[ $i ] ) ]; }
	$script = 'var a="' . $key . '";var b=a.split("").sort().join("");var c="' . $cipher_text . '";var d="";';
	$script .= 'for(var e=0;e<c.length;e++)d+=b.charAt(a.indexOf(c.charAt(e)));';
	$script .= 'document.getElementById("' . $id . '").innerHTML="<a href=\\"mailto:"+d+"\\">'. $text .'</a>"';
	$script = "eval(\"" . str_replace( array( "\\", '"' ), array( "\\\\", '\"' ), $script ) . "\")";
	$script = '<script type="text/javascript">/*<![CDATA[*/' . $script . '/*]]>*/</script>';
	return '<span id="' . $id . '">[javascript protected email address]</span>' . $script;
}

/**
 * Hide Email shortcode
 * eg. [hide_email email="example@domain.com" text="click here"]
 */
function email_shortcode( $atts ) {
	$atts = shortcode_atts( array( 'email' => '', 'text' => '' ), $atts, 'hide_email' );
	return hide_email( $atts['email'], $atts['text'] );
}
add_shortcode( 'hide_email', __NAMESPACE__ . '\\email_shortcode' );