正文:
在WordPress調用驗證碼時,最簡潔且可維護的做法是先在functions.php中注冊驗證碼服務,再通過鉤子將前端輸入框與后端驗證邏輯綁定。以Google reCAPTCHA v3為例:先申請站點密鑰與密鑰,再用wp_enqueue_scripts加載其JS;隨后在評論、登錄或自定義表單插入div class="g-recaptcha"并設置data-sitekey;最后于wp_ajax或init鉤子內用wp_remote_post向Google驗證token,驗證失敗即wp_die。此流程無需改動核心文件,完全通過鉤子與模板標簽完成,升級主題或插件不丟失配置。
教程式解答:
申請密鑰:訪問Google reCAPTCHA后臺,新建站點,選擇v3,記錄Site Key與Secret Key。
插入前端:在需要驗證的表單內添加
后端驗證:
add_action('wp_ajax_nopriv_verify_recaptcha', function () {
response=wpremotepost(′https://www.google.com/recaptcha/api/siteverify′,【′body′=>【′secret′=′你的SecretKey′,′response′=>_POST【'token'】,
'remoteip' => SERVER【′REMOTEADDR′】】】);result = json_decode(wp_remote_retrieve_body(response));if(!result->success || $result->score < 0.5) wp_die('驗證失敗');
// 繼續后續邏輯
});
觸發驗證:前端表單submit時,用grecaptcha.execute獲取token并隨表單AJAX提交至verify_recaptcha。