本教程演示瞭如何將Google的Recaptcha集成到WordPress註冊表中,以打擊垃圾郵件註冊。 我們將利用WordPress HTTP API來驗證用戶響應。
>密鑰概念:
WordPress的受歡迎程度使其成為創建眾多垃圾郵件帳戶的機器人的主要目標。 recaptcha為此問題提供了強大的解決方案。
>插件開發步驟:
獲取recaptcha鍵:
> 插件標頭:
使用標準插件標頭開始插件文件(
recaptcha-registration.php
<code class="language-php"><?php /** * Plugin Name: reCAPTCHA Registration * Plugin URI: [Your Plugin URI] * Description: Adds reCAPTCHA to the WordPress registration form. * Version: 1.0.0 * Author: [Your Name] * Author URI: [Your Website] * License: GPL2 * License URI: https://www.gnu.org/licenses/gpl-2.0.html * Text Domain: recaptcha-registration */</code>
<code class="language-php">class reCAPTCHA_Registration { private $site_key; private $secret_key; public function __construct() { $this->site_key = '[YOUR_SITE_KEY]'; // Replace with your site key $this->secret_key = '[YOUR_SECRET_KEY]'; // Replace with your secret key add_action('register_form', array($this, 'display_recaptcha')); add_action('registration_errors', array($this, 'validate_recaptcha'), 10, 3); } public function display_recaptcha() { ?> <div class="g-recaptcha" data-sitekey="<?php echo $this->site_key; ?>" data-callback="recaptchaCallback"></div> <input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response"> <?php } public function validate_recaptcha($errors, $sanitized_user_login, $user_email) { $response = isset($_POST['g-recaptcha-response']) ? $_POST['g-recaptcha-response'] : null; if (empty($response)) { $errors->add('empty_recaptcha', __('Please complete the reCAPTCHA.', 'recaptcha-registration')); } else { $verify_response = $this->verify_recaptcha($response); if (!$verify_response['success']) { $errors->add('invalid_recaptcha', __('Invalid reCAPTCHA response.', 'recaptcha-registration')); } } } private function verify_recaptcha($response) { $url = 'https://www.google.com/recaptcha/api/siteverify'; $data = array( 'secret' => $this->secret_key, 'response' => $response, 'remoteip' => $_SERVER['REMOTE_ADDR'] ); $response = wp_remote_post($url, array('body' => $data)); return json_decode(wp_remote_retrieve_body($response), true); } } new reCAPTCHA_Registration();</code>到您的
recaptcha-registration.php
屏幕截圖:/wp-content/plugins/
>
這個改進的版本使用了較新的Recaptcha V2和異步加載,以獲得更好的性能和用戶體驗。 它還包括錯誤處理和國際化。 切記用實際的recaptcha鍵替換包圍的佔位符。 該代碼比原始示例更簡潔,更高效。 >
以上是將驗證驗與WordPress註冊表相結合的詳細內容。更多資訊請關注PHP中文網其他相關文章!