防止机器人扫描邮箱

该插件实现了防止机器人扫描邮箱的功能,并使用了 JavaScript 动态拼接邮箱地址来增强防护。

使用方法

在文章或页面中添加电子邮件地址

假设您想显示邮箱 ,只需在编辑文章或页面时插入以下短代码:

[email]admin@wpexp.cn[/email]

查看效果

当您预览或发布这篇文章/页面时,您会看到一个经过 HTML 实体编码和 JavaScript 动态拼接处理后的电子邮件链接。对于大多数用户来说,它看起来就像一个普通的邮件链接,但对机器人来说,获取该邮箱地址变得困难得多。

使用前后对比

使用“防止机器人扫描邮箱”插件之前
使用“防止机器人扫描邮箱”插件之后

插件安装

在 wp-content/plugins 目录下创建一个 wpexp-email.php 文件,将下方代码复制到文件里保存,然后在 WordPress 后台启用该插件。

<?php
/*
Plugin Name: WPEXP - 防止机器人扫描邮箱
Plugin URI: https://wpexp.cn/plugins/email
Description: 使用 HTML 实体编码和 JavaScript 动态拼接保护电子邮件地址不被机器人扫描。
Version: 1.0
Author: WPEXP
Author URI: https://wpexp.cn/
Text Domain: wpexp-email
*/

/**
 * WordPress 防止机器人扫描邮箱(增强版:JS 动态拼接 + HTML 混淆)
 */
function Bing_antispambot_enhanced( $atts, $content = null ) {
    // 清理并验证邮箱
    $email = sanitize_email( $content );
    if ( ! is_email( $email ) ) {
        return '';
    }

    // 拆分邮箱为用户名和域名
    list( $user, $domain ) = explode( '@', $email );

    // 使用 JavaScript 动态拼接邮箱
    $output = '<span class="email-protect">';
    $output .= '<script>';
    $output .= 'document.write(\'<a href="mailto:' . $user . '&#64;' . $domain . '">' . $user . '&#64;' . $domain . '</a>\');';
    $output .= '</script>';

    // 不支持 JS 的情况下显示混淆后的邮箱(如爬虫或禁用 JS 的浏览器)
    $output .= '<noscript>';
    $output .= '<a href="mailto:' . antispambot( $email ) . '">' . antispambot( $email ) . '</a>';
    $output .= '</noscript>';

    $output .= '</span>';

    return $output;
}
add_shortcode( 'email', 'Bing_antispambot_enhanced' );

/**
 * 插件激活时的钩子
 */
function wpexp_email_activate() {
    // 可以在这里添加激活插件时需要执行的代码
}

register_activation_hook( __FILE__, 'wpexp_email_activate' );

/**
 * 插件停用时的钩子
 */
function wpexp_email_deactivate() {
    // 可以在这里添加停用插件时需要执行的代码
}

register_deactivation_hook( __FILE__, 'wpexp_email_deactivate' );