本教程演示了如何将Google的Recaptcha集成到WordPress注册表中,以打击垃圾邮件注册。 我们将利用WordPress HTTP API来验证用户响应。
>密钥概念:
WordPress的受欢迎程度使其成为创建众多垃圾邮件帐户的机器人的主要目标。 recaptcha为此问题提供了强大的解决方案。
>插件开发步骤:
获取recaptcha键:
> 插件标头:
使用标准插件标头开始插件文件(
recaptcha-registration.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 */
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();
recaptcha-registration.php
屏幕截图:/wp-content/plugins/
>
这个改进的版本使用了较新的Recaptcha V2和异步加载,以获得更好的性能和用户体验。 它还包括错误处理和国际化。 切记用实际的recaptcha键替换包围的占位符。 该代码比原始示例更简洁,更高效。>
以上是将验证验与WordPress注册表相结合的详细内容。更多信息请关注PHP中文网其他相关文章!