implement reCAPTCHA v3 in WordPress loginscreen
First of all, make sure to enable JavaScript
. If not, refer to this link at reCaptcha faq.
I've tested the following code without any error and had reCaptcha Logo in the bottom right corner:
reCaptchaV3/reCaptchaV3.php
<?php
/*
* Plugin Name: reCaptchaV3 Beta
* Plugin Author: N/A
* Version: 0.1
*/
final class reCaptchaV3
{
public function __construct() { }
public function init()
{
add_action( 'login_enqueue_scripts', array($this, 'load_login_scripts') );
}
public static function load_login_scripts()
{
wp_enqueue_script( 'recaptchav3', 'https://www.google.com/recaptcha/api.js?render=SITE_KEY');
wp_enqueue_script( 'custom-recaptcha', plugin_dir_url( __FILE__ ) . 'recaptcha.js' );
}
}
add_action( 'init', array( new reCaptchaV3(), 'init' ) );
reCaptchaV3/recaptcha.js
document.addEventListener("DOMContentLoaded", function(event) {
grecaptcha.ready(function() {
grecaptcha.execute('SITE_KEY', {action:
'login'}).then(function(token) {
console.log(token);
});
});
});
Version Issue
login_enqueue_scripts
was available after WordPress version 3.1.0 so make sure to use WordPress version after that.
API Keys
Get the testing keys from here, not sure if they work for reCaptcha v3 Beta but I had my registered at admin console. Although, localhost is not a supported domain so use a virtual host if you're working locally.
If you have added or changed domains in admin console, it takes 30 minutes to effect the change
Testing Keys:
Site Key: 6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI
Secret Key: 6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe
Accessibility
If you're not seeing reCaptcha logo, maybe google.com
is not accessible for script loading. Try to replace it with recaptcha.net
like this:
wp_enqueue_script( 'recaptchav3', 'https://www.recaptcha.net/recaptcha/api.js?render=SITE_KEY');
If you're using Content-Security-Policy (CSP) on your website, please review reCaptcha faq