In this post, you will learn how to add Google reCAPTCHA to the WordPress comment section, admin login page, lost password page, and registration form.

First, go to the following address and add your domain to it in the Google recaptcha dashboard.
https://www.google.com/recaptcha/admin/create

Fill out the above form as follows:

  1. Write a label for your site
  2. Choose reCAPTCHA v2
  3. Choose [“I’m not a robot” Checkbox]
  4. Enter your domain address.
  5. Enter the email address of the site administrator.
  6. Accept the reCAPTCHA Terms of Service

Then click on the submit button.

After submitting the form, you will receive the site key and secret key for your site. We will use these two inside our code.

Write the site key and secret key in the code below and in the WordPress dashboard, go to Appearance ➡ Theme File Editor and insert it into the theme’s functions.php file and save it.

You must create a child theme before making any changes to functions.php file. Otherwise, the applied changes will be lost after each update.
Create child theme in WordPress step by step [without plugin]

As an alternative method, you can use the Code Snippets plugin to insert your codes into WordPress.

function my_recaptcha_key(){
	$sitekey= "00000000000000000000000000000";
	$secretkey= "00000000000000000000000000000";
	return explode(",", $sitekey.",".$secretkey ); 	
}

Add reCAPTCHA to WordPress Comment Section

To add Google RecCaptcha to the comments section of the posts, copy the following code into the functions.php file of your theme and save it.

Show code
/*
*Add reCAPTCHA to WordPress Comment Section
*/
add_action( 'wp_head', function(){
wp_enqueue_script('google-recaptcha', 'https://www.google.com/recaptcha/api.js');
} );
function add_google_recaptcha($submit_field) {
    $submit_field['submit_field'] = '<div class="g-recaptcha" data-sitekey="'.my_recaptcha_key()[0].'"></div><br>' . $submit_field['submit_field'];
    return $submit_field;
}
if (!is_user_logged_in()) {
    add_filter('comment_form_defaults','add_google_recaptcha');
}
function is_valid_captcha($captcha) {
$captcha_postdata = http_build_query(array(
                            'secret' => my_recaptcha_key()[1],
                            'response' => $captcha,
                            'remoteip' => $_SERVER['REMOTE_ADDR']));
$captcha_opts = array('http' => array(
                      'method'  => 'POST',
                      'header'  => 'Content-type: application/x-www-form-urlencoded',
                      'content' => $captcha_postdata));
$captcha_context  = stream_context_create($captcha_opts);
$captcha_response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify" , false , $captcha_context), true);
if ($captcha_response['success'])
    return true;
else
    return false;
}
 
function verify_google_recaptcha() {
$recaptcha = $_POST['g-recaptcha-response'];
if (empty($recaptcha))
    wp_die( __("<b>ERROR:</b> please select <b>I'm not a robot!</b><p><a href='javascript:history.back()'>« Back</a></p>"));
else if (!is_valid_captcha($recaptcha))
    wp_die( __("<b>Go away SPAMMER!</b>"));
}
if (!is_user_logged_in()) {
    add_action('pre_comment_on_post', 'verify_google_recaptcha');
}

Add reCaptcha on WordPress Admin Login Page Without Plugin

To add Google RecCaptcha on WordPress Admin Login Page, copy the following code into the functions.php file of your theme and save it.

Show code
/*
*Add reCaptcha on WordPress Admin Login Page Without Plugin
*/

function login_style() {
    wp_register_script('login-recaptcha', 'https://www.google.com/recaptcha/api.js', false, NULL);
    wp_enqueue_script('login-recaptcha');
	echo "<style>p.submit, p.forgetmenot {margin-top: 10px!important;}.login form{width: 303px;} div#login_error {width: 322px;}</style>";
}
add_action('login_enqueue_scripts', 'login_style');
function add_recaptcha_on_login_page() {
    echo '<div class="g-recaptcha brochure__form__captcha" data-sitekey="'.my_recaptcha_key()[0].'"></div>';
}
add_action('login_form','add_recaptcha_on_login_page');
function captcha_login_check($user, $password) {
    if (!empty($_POST['g-recaptcha-response'])) {
        $secret = my_recaptcha_key()[1];
        $ip = $_SERVER['REMOTE_ADDR'];
        $captcha = $_POST['g-recaptcha-response'];
        $rsp = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' . $secret . '&response=' . $captcha .'&remoteip='. $ip);
        $valid = json_decode($rsp, true);
        if ($valid["success"] == true) {
            return $user;
        } else {
            return new WP_Error('Captcha Invalid', __('<center>Captcha Invalid! Please check the captcha!</center>'));
        }
    } else {
        return new WP_Error('Captcha Invalid', __('<center>Captcha Invalid! Please check the captcha!</center>'));
    }
}
add_action('wp_authenticate_user', 'captcha_login_check', 10, 2);

Add reCaptcha to WordPress Lost Password Form Without Plugin

To add Google RecCaptcha to Lost Password Form, copy the following code into the functions.php file of your theme and save it.

Show code

This code is for WPCookie PLUS+ members only.

Join WPCookie PLUS+
Already a member? Log in here

Add reCaptcha to WordPress registration Form Without Plugin

To add Google RecCaptcha to registration Form, copy the following code into the functions.php file of your theme and save it.

Show code

This code is for WPCookie PLUS+ members only.

Join WPCookie PLUS+
Already a member? Log in here

If this article is difficult for you to read in text, you can watch the video version below.

You may also like:
Add Cloudflare Turnstile CAPTCHA in WordPress without Plugins

Share this post
Maya
Maya

Hi, my name is Maya and I’m a WordPress plugin developer. I created this website to share some of the helpful codes that I’ve used in my own projects.
If you’re looking for a custom plugin for your website, you can contact me by clicking on Hire a developer in the menu. I’d love to hear from you.

Articles: 56

14 Comments

  1. Hello
    I have all the steps of getting the code and inserting them correctly in the PHP child theme, and I got wordpress approval.
    When logging in to enter the WordPress counter, when I tick the recaptcha, it confirms and enters without any dialog. At the top of the login page, it also declares an unreal recaptcha. Why?

    • متوجه نشدم چی نوشتی، تا چند وقت دیگه ورژن فارسی این آموزشارو میذارم تو سایت mrnargil.ir بعدا برو چکش کن

  2. Hello, How are you?
    How can i custom add more space, i mean blank space (2, 3, 4 pixel,.) between button reCAPTCHA with Post comment button.
    example: ibb.co/C8fzfPk

    • To add more space between the reCAPTCHA and other fields, modify your website\’s CSS file by adding a margin to the g-recaptcha class:

      .g-recaptcha {
      margin-bottom: 20px;
      margin-top: 20px;
      }

      Adjust the margin value to increase or decrease the space as needed. Save the CSS file, update it on your website (if necessary), and refresh the page to see the changes.

  3. Add reCaptcha to WordPress registration is not working,
    Error: Could not update snippet. Request failed with status code 403

    and how can we add in woocommerce account page?

    • The 403 forbidden code usually means that something is blocking the connection — it could be on-site from some caching or security plugin, or at server-level. As a first step, I would recommend purging and disabling any caching plugins you may have running on the site, followed by disabling any security plugins.

    • Great question! I\’ll definitely create a tutorial about this in the future. Thanks for bringing this up!

      • I don\’t think there has been any progress yet. I\’m looking forward. Do you have an estimated timing plan? Kind regards…

        • Hey there! I hope you\’re doing well. Right now, I\’m occupied with a few other tasks, so I don\’t think I\’ll be able to work on your requested tutorial anytime soon. However, if you\’re in a hurry, I\’d love to help you out by coding a project exclusively for you. Just define it on the site, and I\’ll get right on it!

Leave a Reply

Your email address will not be published. Required fields are marked *