函数文档

antispambot()

💡 云策文档标注

概述

antispambot() 是 WordPress 核心函数,用于将电子邮件地址字符转换为 HTML 实体,以阻止垃圾邮件机器人抓取。它接受电子邮件地址和可选编码参数,返回转换后的字符串。

关键要点

  • 函数作用:通过 HTML 实体编码混淆电子邮件地址,防止被垃圾邮件机器人识别。
  • 参数:$email_address(必需,字符串类型,电子邮件地址);$hex_encoding(可选,整数类型,设置为 1 启用十六进制编码)。
  • 返回值:字符串类型,转换后的电子邮件地址。
  • 相关函数:zeroise() 用于添加前导零。
  • 版本历史:自 WordPress 0.71 版本引入。

代码示例

/**
 * Hide email from Spam Bots using a shortcode.
 *
 * @param array  $atts    Shortcode attributes. Not used.
 * @param string $content The shortcode content. Should be an email address.
 * @return string The obfuscated email address. 
 */
function wpdocs_hide_email_shortcode( $atts , $content = null ) {
    if ( ! is_email( $content ) ) {
        return;
    }
    return '' . esc_html( antispambot( $content ) ) . '';
}
add_shortcode( 'email', 'wpdocs_hide_email_shortcode' );

注意事项

  • 在 href 属性中使用时,esc_attr() 比 esc_html() 更合适,以避免添加不必要的 http:// 前缀。
  • 从 WordPress 4.8 开始,文本小工具默认支持短代码,无需额外添加 widget_text 过滤器。
  • 用户反馈指出,HTML 实体编码可能已不足以有效阻止现代垃圾邮件机器人,建议考虑更高级的混淆技术如 Xor。

📄 原文内容

Converts email addresses characters to HTML entities to block spam bots.

Parameters

$email_addressstringrequired
Email address.
$hex_encodingintoptional
Set to 1 to enable hex encoding.

Return

string Converted email address.

Source

function antispambot( $email_address, $hex_encoding = 0 ) {
	$email_no_spam_address = '';

	for ( $i = 0, $len = strlen( $email_address ); $i < $len; $i++ ) {
		$j = rand( 0, 1 + $hex_encoding );

		if ( 0 === $j ) {
			$email_no_spam_address .= '&#' . ord( $email_address[ $i ] ) . ';';
		} elseif ( 1 === $j ) {
			$email_no_spam_address .= $email_address[ $i ];
		} elseif ( 2 === $j ) {
			$email_no_spam_address .= '%' . zeroise( dechex( ord( $email_address[ $i ] ) ), 2 );
		}
	}

	return str_replace( '@', '@', $email_no_spam_address );
}

Changelog

Version Description
0.71 Introduced.

User Contributed Notes

  1. Skip to note 3 content

    Example

    /**
     * Hide email from Spam Bots using a shortcode.
     *
     * @param array  $atts    Shortcode attributes. Not used.
     * @param string $content The shortcode content. Should be an email address.
     * @return string The obfuscated email address. 
     */
    function wpdocs_hide_email_shortcode( $atts , $content = null ) {
    	if ( ! is_email( $content ) ) {
    		return;
    	}
    	return '<a href="' . esc_url('mailto:' . antispambot( $content ) ) . '">' . esc_html( antispambot( $content ) ) . '</a>';
    }
    add_shortcode( 'email', 'wpdocs_hide_email_shortcode' );

    To use this in your WordPress Content area all you have to do it wrap it in a short code.

    [email]john.doe@mysite.com[/email]

    You can also use this in a plain text widget if you add this filter to your function file as well.

    add_filter( 'widget_text', 'shortcode_unautop' );
    add_filter( 'widget_text', 'do_shortcode' );

    Edited with a contribution from @johnrafferty