Last active
November 12, 2024 18:13
-
-
Save mohsinworld/bfd8c00725e617a1109a473f1f60645c to your computer and use it in GitHub Desktop.
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
// Add Math CAPTCHA to WooCommerce Checkout | |
add_action('woocommerce_after_order_notes', 'custom_math_captcha_checkout'); | |
function custom_math_captcha_checkout($checkout) { | |
$num1 = rand(1, 10); // Generate first random number | |
$num2 = rand(1, 10); // Generate second random number | |
$sum = $num1 + $num2; // Calculate the sum | |
// Store the sum in a session for later validation | |
WC()->session->set('math_captcha_sum', $sum); | |
echo '<div id="math-captcha">'; | |
echo '<p><strong>Anti-spam verification:</strong></p>'; | |
echo '<p>What is ' . $num1 . ' + ' . $num2 . '?</p>'; | |
woocommerce_form_field('math_captcha', [ | |
'type' => 'number', | |
'class' => ['form-row-wide'], | |
'required' => true, | |
'placeholder' => 'Enter the result', | |
], $checkout->get_value('math_captcha')); | |
echo '</div>'; | |
} | |
// Validate Math CAPTCHA on Checkout | |
add_action('woocommerce_checkout_process', 'custom_math_captcha_validate'); | |
function custom_math_captcha_validate() { | |
$sum = WC()->session->get('math_captcha_sum'); | |
$answer = isset($_POST['math_captcha']) ? intval($_POST['math_captcha']) : 0; | |
if ($answer !== $sum) { | |
wc_add_notice(__('Incorrect anti-spam answer. Please try again.', 'woocommerce'), 'error'); | |
} | |
} | |
// Clear Math CAPTCHA after Order Completion | |
add_action('woocommerce_thankyou', 'custom_math_captcha_clear_session'); | |
function custom_math_captcha_clear_session() { | |
WC()->session->__unset('math_captcha_sum'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment