Using WordPress ‘antispambot()’ PHP function

The antispambot() WordPress PHP function converts email addresses characters to HTML entities in order to prevent spam bots from harvesting them. It’s a handy tool for safeguarding your email addresses in your WordPress site from unwanted spams.

Usage

Here’s how you might use the function to obfuscate an email address:

$email = "[email protected]";
$safe_email = antispambot($email);
echo $safe_email;  // Prints the obfuscated email

In this example, the output would be an obfuscated version of ‘[email protected]’.

Parameters

  • $email_address (string): The email address that you want to obfuscate.
  • $hex_encoding (int): An optional parameter. Set to 1 to enable hex encoding of the email.

More information

See WordPress Developer Resources: antispambot
This function is part of the WordPress core and is well-maintained. It’s not deprecated and should continue working for the foreseeable future.

Examples

Basic usage

$email = "[email protected]";
$safe_email = antispambot($email);
echo $safe_email;  // Prints obfuscated email

This code obfuscates the given email address and then prints it.

Enabling hex encoding

$email = "[email protected]";
$safe_email = antispambot($email, 1);
echo $safe_email;  // Prints obfuscated email with hex encoding

In this example, we are also enabling hex encoding by passing 1 as the second parameter to the **antispambot()** function.

$email = "[email protected]";
$safe_email = antispambot($email);
echo '<a href="mailto:' . $safe_email . '">Email me</a>';

This code creates a clickable email link that is safe from spam bots.

Use in a shortcode to hide email

function wpdocs_hide_email_shortcode($atts, $content = null) {
    if (!is_email($content)) {
        return;
    }
    return '<a href="mailto:' . esc_url(antispambot($content)) . '">' . esc_html(antispambot($content)) . '</a>';
}
add_shortcode('email', 'wpdocs_hide_email_shortcode');

This code creates a WordPress shortcode that obfuscates the email address within.

Use shortcode in content

// In your WordPress content area, you can now use:
[email][email protected][/email]

This code demonstrates how you can use the created shortcode in your content area to obfuscate email addresses.