You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为WordPress全站添加CAPTCHA验证 访客每6小时仅需验证一次

实现思路

核心采用「前端Cookie存验证状态+全页面拦截」的逻辑,完全通过前端代码实现,无需修改服务端配置或安装插件:

  • 页面加载时优先检查客户端是否存储了验证通过的Cookie
  • 无有效Cookie时显示CAPTCHA验证遮罩,完全隐藏站点内容
  • 验证通过后写入有效期为6小时的全站Cookie,后续访问直接放行
  • 爬虫不支持JS执行与CAPTCHA交互,自然无法抓取内容,满足搜索引擎隐藏需求
具体实现方案

所有代码直接插入WordPress的头部、页脚脚本位置即可生效,不需要额外配置。

头部插入代码

<style>
/* 避免验证前页面内容闪现 */
body {
    display: none !important;
}
/* CAPTCHA遮罩层样式 */
.captcha-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    background: #ffffff;
    z-index: 999999;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    gap: 20px;
}
</style>
<script>
// 读取Cookie的通用方法
function getCookie(name) {
    let value = "; " + document.cookie;
    let parts = value.split("; " + name + "=");
    if (parts.length === 2) return parts.pop().split(";").shift();
}
const isCaptchaPassed = getCookie('site_captcha_pass');
// 未通过验证则渲染验证遮罩
if (!isCaptchaPassed) {
    document.write(`
    <div class="captcha-overlay">
        <h3>请完成验证后访问站点</h3>
        <div id="captcha-box"></div>
    </div>
    `);
} else {
    // 验证通过直接显示页面内容
    document.body.style.display = 'block';
}
</script>

页脚插入代码

<script>
if (!getCookie('site_captcha_pass')) {
    // 加载CAPTCHA资源,替换为你选用的CAPTCHA服务对应的JS地址
    const captchaScript = document.createElement('script');
    captchaScript.src = "你使用的CAPTCHA服务的JS资源地址";
    captchaScript.onload = function() {
        // 渲染CAPTCHA组件,参数根据你选用的CAPTCHA服务调整
        yourCaptchaObj.render('captcha-box', {
            sitekey: '你申请的CAPTCHA站点密钥',
            callback: function(verifyToken) {
                // 验证通过后写入6小时有效期的全站Cookie
                let expire = new Date();
                expire.setTime(expire.getTime() + 6 * 60 * 60 * 1000);
                document.cookie = `site_captcha_pass=1; expires=${expire.toUTCString()}; path=/; SameSite=Lax`;
                // 移除遮罩显示页面
                document.querySelector('.captcha-overlay').remove();
                document.body.style.display = 'block';
            }
        })
    }
    document.head.appendChild(captchaScript);
}
</script>
注意事项
  • 代码中CAPTCHA的渲染逻辑、验证回调可根据你选择的CAPTCHA类型(自定义滑块、算术验证、第三方CAPTCHA服务)灵活调整,核心状态存储与拦截逻辑不变
  • 方案兼容WordPress静态缓存,所有逻辑在客户端执行,不会和缓存规则冲突
  • 如果需要调整验证有效期,仅需要修改Cookie写入时的6 * 60 * 60 * 1000参数即可,单位为毫秒

内容的提问来源于stack exchange,提问作者Piyush Verma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 09:06:05