Notice: WP_Scripts::localize was called incorrectly. The $l10n parameter must be an array. To pass arbitrary data to scripts, use the wp_add_inline_script() function instead. Please see Debugging in WordPress for more information. (This message was added in version 5.7.0.) in /home/customer/www/pixelnet.in/public_html/wp-includes/functions.php on line 5313
Add Google reCAPTCHA on WordPress Comment Forms
HOME»Blog»Tutorials»How To Add Google reCAPTCHA on WordPress Comment…

How To Add Google reCAPTCHA on WordPress Comment Form

Advertise Here
Google reCAPTCHA Logo

Getting too many SPAM comments that even Akismet can’t handle? You need to add Google reCAPTCHA on WordPress comment form to get rid of the bot comments and potential SPAMs. Google reCAPTCHA basically prevents comment bots and link harvesters by adding an extra layer of checks before submitting the comments.

There are several Google reCAPTCHA methods we can work on, for example, an invisible badge which automatically validates the request in the background (APIv2) or using a scoring system to manually determine the nature of the request (APIv3), but we will integrate the most popular “I’m not a robot” checkbox method on which users have to pass a security challenge in order be validated.

Though there are several plugins available for this, but if you want customization and complete control over the setup, you should go with the custom coding.

First things first, get your own site key and secret.

Add Google reCAPTCHA on WordPress Comment Form

Now, let’s add Google reCAPTCHA on WordPress Comment form. There are several ways to programmatically add the field, like using comment_form hook which fires just above the closing form tag of the comment form, but that would make the reCAPTCHA checkbox appear AFTER submit button.

I personally prefer using the comment_form_after_fields hook with a very low priority to make the checkbox appear as the last field before the submit button.

function pixelnet_add_recaptcha_field() {

	//Add the div
	echo '<div id="commentcaptcha"></div>';
	
}
add_action( 'comment_form_after_fields', 'pixelnet_add_recaptcha_field', 999 );

Now we disable the submit button to prevent comment submission before anyone passes the challenge. This is totally optional but looks cool when someone passes the challenge and the button becomes active.

function pixelnet_filter_comment_fields( $defaults ) {
	
	//Add the 'disabled' attribute to the button
	$defaults['submit_button'] = '<input name="%1$s" type="submit" id="%2$s" class="%3$s" value="%4$s" disabled="disabled">';
	
	return $defaults;

}
add_filter( 'comment_form_defaults', 'pixelnet_filter_comment_fields' );

The third step would be enqueuing required JavaScript file and necessary initiation code. Replace the site key with your own.

function pixelnet_enqueue_scripts() {

	//Enqueue reCAPTCHA JavaScript file and initiation code
	if ( is_singular() && comments_open() ) {
		wp_enqueue_script( 'gcaptcha', 'https://www.google.com/recaptcha/api.js?onload=gcaptchaOLCB&render=explicit', array(), null, true );
		wp_add_inline_script( 'gcaptcha', 'var gcaptchaOLCB = function() {
			grecaptcha.render( "commentcaptcha", {
				"sitekey" : "YOUR_SITE_KEY_HERE", //Replace this
				"callback" : function(response) {
					document.getElementById("submit").removeAttribute("disabled");
				},
				"expired-callback" : function(response) {
					document.getElementById("submit").setAttribute("disabled", "disabled");
				},

			});
		  };', 'before');
	}
}
add_action( 'wp_enqueue_scripts', 'pixelnet_enqueue_scripts' );

Lastly, validate the request before submit the comment and show error messages if anyone fails to be proven human.

function pixelnet_validate_recaptcha( $commentdata ) {
	
	if ( !isset($_POST['g-recaptcha-response']) || empty($_POST['g-recaptcha-response']) ) {
		wp_die( __( 'Captcha Field is Required', 'pixelnet' ) );
	}
	
	$gresponse = wp_remote_post( 'https://www.google.com/recaptcha/api/siteverify', array(
		'body' => array(
			'secret' => 'YOUR_SITE_SECRET_KEY_HERE',
			'response' => $_POST['g-recaptcha-response']
		),
	));
	
	if ( is_wp_error( $gresponse ) ) {
		wp_die($gresponse->get_error_message());
	} else {
		$body = json_decode(wp_remote_retrieve_body($gresponse));
		if ( !$body->success  ) {
			wp_die( __( 'Looks like you are not a human', 'pixelnet' ) );
		}
	}
	return $commentdata;
}
add_filter( 'preprocess_comment', 'pixelnet_validate_recaptcha' );

Replace the secret with your own.

That’s how you add Google reCAPTCHA on WordPress comment form, enjoy lesser SPAM comments, and do let me know in a comment if you face any issues while implementing this.

Leave a comment

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

1 Comment

  1. Nice post, thanks for sharing. It seems to only work for v2 recaptchas. Also, I’d add the action:

    add_action( 'comment_form_logged_in_after', 'pixelnet_add_recaptcha_field', 999 );

    for the pixelnet_add_recaptcha_field function to show the recaptcha for logged in users.

    Cheers!

Join PixelNet Community

+ + + + = 1,230

Join our mailing list and get exiting WordPress resources and offers directly in your Inbox.No SPAM Promise

Advertise Here