Hide Email Addresses From Spam Bots
Encodes every email address and mailto link in posts, widgets and comments so people see them normally but simple harvesting bots cannot read them.
Opens WPIDE on
Code
$wpide_protect_emails = function ( $content ) {
if ( false === strpos( (string) $content, '@' ) ) {
return $content;
}
$parts = preg_split( '/(<[^>]+>)/', $content, -1, PREG_SPLIT_DELIM_CAPTURE );
$in_script = false;
foreach ( $parts as $i => $part ) {
if ( '' === $part ) {
continue;
}
if ( '<' === $part[0] ) {
if ( preg_match( '#^<(script|style|textarea)\b#i', $part ) ) {
$in_script = true;
} elseif ( preg_match( '#^</(script|style|textarea)>#i', $part ) ) {
$in_script = false;
}
$parts[ $i ] = preg_replace_callback( '/href=(["\'])mailto:([^"\']+)\1/i', function ( $m ) {
return 'href=' . $m[1] . 'mailto:' . antispambot( $m[2] ) . $m[1];
}, $part );
continue;
}
if ( ! $in_script ) {
$parts[ $i ] = preg_replace_callback( '/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i', function ( $m ) {
return antispambot( $m[0] );
}, $part );
}
}
return implode( '', $parts );
};
add_filter( 'the_content', $wpide_protect_emails, 99 );
add_filter( 'widget_text', $wpide_protect_emails, 99 );
add_filter( 'widget_block_content', $wpide_protect_emails, 99 );
add_filter( 'comment_text', $wpide_protect_emails, 99 );
Notes
Determined scrapers that decode HTML entities can still read the addresses.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.