Last active
September 9, 2017 17:29
-
-
Save kenmasters/75bdf191f850409e88b75f2f3181d760 to your computer and use it in GitHub Desktop.
Creating a custom math captcha in gravityform in a form of a shortcode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Paste code from `gform-math-captcha.txt` in your current themes functions.php | |
// Then add an HTML field in gravityform where you want to have a math captcha | |
// Then add the shortcode: [math-captcha form=yourformID] | |
-How it works? | |
// Submit button will be disabled by default, and will be enabled when entering the correct answer to a math equation. | |
add_shortcode('math-captcha', 'math_captcha'); | |
function math_captcha ($atts = [], $content = null) { | |
// normalize attribute keys, lowercase | |
$atts = array_change_key_case((array)$atts, CASE_LOWER); | |
// override default attributes with user attributes | |
extract( shortcode_atts([ | |
'form' => 0, | |
], $atts, 'math-captcha') ); | |
ob_start(); | |
?> | |
<div class="math-captcha"> | |
<h3 id='captchalabel'></h3> | |
<input type="text" id="captchaanswer"> | |
</div> | |
<script> | |
jQuery( function($) { | |
var submitButton = $('#gform_submit_button_' + <?=$form?>); | |
// Disable submit button by default | |
submitButton.prop('disabled', true).addClass('disabled'); | |
var num_1 = Math.floor((Math.random() * 10) + 1); | |
var num_2 = Math.floor((Math.random() * 10) + 1); | |
var sum = num_1 + num_2; | |
$('#captchalabel').text(num_1.toString() + ' + ' + num_2.toString()); | |
$('#captchaanswer').keyup(function(){ | |
submitButton.prop('disabled', true).addClass('disabled'); | |
if ( parseInt($(this).val()) !== sum ) return false; | |
submitButton.prop('disabled', false).removeClass('disabled') ; | |
}); | |
}) | |
</script> | |
<style> | |
.gform_button.button.disabled { | |
cursor: not-allowed; | |
opacity: .65; | |
} | |
</style> | |
<? | |
return ob_get_clean(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment