STYLE SWITCHER

Add Google reCAPTCHA in WordPress

Google reCAPTCHA is becoming popular since the day of its announcement. The performance of this product is not been evaluated yet because of its age.

I have covered basic tutorial about how to code custom script with Google reCAPTCHA.

functions.php

/*Add Google captcha field to Comment form*/

add_filter('comment_form','add_google_captcha');

function add_google_captcha(){
echo '<div class="g-recaptcha" data-sitekey= "=== Your site key === "></div>';
}

/*End of Google captcha*/

single.php

<script src='https://www.google.com/recaptcha/api.js'></script>
<script type="text/javascript">
jQuery("#submit").click(function(e){
var data_2;
jQuery.ajax({
type: "POST",
url: "http://yourblog.com/wp-content/themes/yourtheme/google_captcha.php",
data: jQuery('#commentform').serialize(),
async:false,
success: function(data) {
if(data.nocaptcha==="true") {
data_2=1;
} else if(data.spam==="true") {
data_2=1;
} else {
data_2=0;
}
}
});
if(data_2!=0) {
e.preventDefault();
if(data_2==1) {
alert("Please check the captcha");
} else {
alert("Please Don't spam");
}
} else {
jQuery("#commentform").submit
}
});
</script>

google_captcha.php

<?php
$data;
header('Content-Type: application/json');
error_reporting(E_ALL ^ E_NOTICE);
if(isset($_POST['g-recaptcha-response'])) {
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
$data=array('nocaptcha' => 'true');
echo json_encode($data);
exit;
}
// calling google recaptcha api.
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=Your secret key&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
// validating result.
if($response.success==false) {
$data=array('spam' => 'true');
echo json_encode($data);
} else {
$data=array('spam' => 'false');
echo json_encode($data);
}
?>

Website

Recent Article

Leave a Reply

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

  1. Hi Anish,

    I saw your tweet about wordpress and i recommend you to come to my website! You will love it! You can find Plugins for WordPress for only 2-3 bucks. JvZoo Products for 4-9 bucks… Trust me! Its the heaven for any website owner!!
    Please visit us and that your conclusion 😀

    https://goo.gl/EcEwTW or netafiliados. com

    Keep making great stuff!