# 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.

- Type: PHP
- Runs: Frontend only
- Category: [Security](https://wpide.com/library/category/security/)
- Tags: security, spam, email
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/hide-email-addresses-from-bots/

## Code

```php
$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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Hide Email Addresses From Spam Bots" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
