在 WordPress 评论中集成 Cloudflare Turnstile
将密钥存储在 wp-config.php
中,并将验证代码放在 functions.php
中。
更新内容:
2025-03-26 第一版发布
2025-03-30 修复了一些错误,Cloudflare Turnstile 验证将只在 WordPress 前台未登录的用户提交评论时才会出现和进行验证,从而提供更好的用户体验。
1. wp-config.php
文件
- 打开你的 WordPress 网站根目录下的
wp-config.php
文件。 - 在
wp-config.php
文件中,添加以下代码,替换你的SiteKey
和你的SecretKey
:
// Cloudflare Turnstile
define('CLOUDFLARE_TURNSTILE_SITE_KEY', '你的SiteKey');
define('CLOUDFLARE_TURNSTILE_SECRET_KEY', '你的SecretKey');
2. functions.php
文件
- 打开你的主题的
functions.php
文件。 - 将以下代码添加到
functions.php
文件中:
// Cloudflare Turnstile
// 向评论表单添加 Turnstile JavaScript
function add_cloudflare_turnstile_to_comment_form() {
if (!is_admin() && !is_user_logged_in() && defined('CLOUDFLARE_TURNSTILE_SITE_KEY')) {
echo '<div class="cf-turnstile" data-sitekey="' . esc_attr(CLOUDFLARE_TURNSTILE_SITE_KEY) . '"></div>';
echo '<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>';
}
}
add_action('comment_form_after_fields', 'add_cloudflare_turnstile_to_comment_form');
// 验证 Turnstile 响应
function verify_cloudflare_turnstile($commentdata) {
// 在后台或已登录用户不进行验证
if (is_admin() || is_user_logged_in()) {
return $commentdata;
}
if (isset($_POST['cf-turnstile-response']) && defined('CLOUDFLARE_TURNSTILE_SECRET_KEY')) {
$secret = CLOUDFLARE_TURNSTILE_SECRET_KEY;
$response = sanitize_text_field($_POST['cf-turnstile-response']);
$remoteip = $_SERVER['REMOTE_ADDR'];
$url = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
$data = array(
'secret' => $secret,
'response' => $response,
'remoteip' => $remoteip
);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$json_result = json_decode($result);
if ($json_result === null || !isset($json_result->success) || $json_result->success !== true) {
wp_die(__('Turnstile verification failed, please try again.', 'your-text-domain'));
}
} else {
wp_die(__('Turnstile was not submitted, please try again.', 'your-text-domain'));
}
return $commentdata;
}
add_filter('preprocess_comment', 'verify_cloudflare_turnstile');
重要说明:
- 替换密钥: 请务必将
"你的SiteKey"
和"你的SecretKey"
替换为你在 Cloudflare Turnstile 中获得的实际密钥。 - 备份: 在编辑
wp-config.php
和functions.php
文件之前,请务必备份你的网站。 - 测试: 在实际部署之前,请彻底测试 Turnstile 是否正常工作。
- 主题更新: 如果你更新了主题,请确保将
functions.php
中的代码重新添加。 - 安全: 妥善保管你的 Secret key.
- 错误处理: 现在的错误处理是使用 wp_die()函数,用来显示错误。 你可以根据自己的需要,修改错误提示的内容。
回复 土木坛子 取消回复