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

如何在WooCommerce商品评价提交按钮前添加reCAPTCHA v2验证

WooCommerce商品评价页添加Google reCAPTCHA v2解决方案

原有代码失效的核心原因是WooCommerce商品评论表单使用独立的钩子体系,普通文章的评论钩子和single.php的脚本加载逻辑不会作用于商品页,按以下步骤修改即可:


第一步:调整reCAPTCHA脚本加载逻辑

删掉原来添加到single.php的脚本加载代码,改成在主题functions.php中添加如下代码,仅在未登录用户访问商品详情页时加载脚本,避免全局冗余加载:

// 仅商品页加载reCAPTCHA脚本
add_action('wp_enqueue_scripts', 'enqueue_recaptcha_for_woo_review');
function enqueue_recaptcha_for_woo_review() {
    if (is_product() && !is_user_logged_in()) {
        wp_enqueue_script('google-recaptcha', 'https://www.google.com/recaptcha/api.js', [], false, true);
    }
}

第二步:适配WooCommerce评论表单钩子,插入验证框

修改原有插入验证框的代码,额外适配WooCommerce商品评论的专属钩子,修改后代码如下:

/**
 * Google recaptcha 加在提交按钮之前
 */
function add_google_recaptcha($submit_field) {
    if (!is_user_logged_in()) {
        $submit_field['submit_field'] = '<div class="g-recaptcha" data-sitekey="your_site_key"></div><br>' . $submit_field['submit_field'];
    }
    return $submit_field;
}
// 同时兼容普通文章评论和WooCommerce商品评论
if (!is_user_logged_in()) {
    add_filter('comment_form_defaults','add_google_recaptcha');
    add_filter('woocommerce_product_review_comment_form_args', 'add_google_recaptcha');
}

第三步:验证逻辑无需修改

原有验证码校验逻辑不需要改动,因为WooCommerce商品评论本质还是WordPress核心的评论体系,pre_comment_on_post钩子会正常触发。


注意事项

  • 替换代码中your_site_key和your_secret_key为你自己申请的reCAPTCHA v2对应密钥
  • 测试前请清除站点缓存,避免旧表单缓存影响效果

内容的提问来源于stack exchange,提问作者Omar Giancarlo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 14:09:00