sinanisler logo

Adding Simple Math Captcha to WordPress Login

this code adds a simple math captcha to wordpress login and you can make the math harder I set the rand numbers to between 1,6 but you can make 1,99 too 🙂

as always add this code to your functions.php or codesnippet plugin.

// Add math captcha to login form with JavaScript validation
function add_login_math_captcha() {
    if (!session_id()) {
        session_start();
    }
    $_SESSION['captcha_number1'] = rand(1, 6);
    $_SESSION['captcha_number2'] = rand(1, 6);
    $sum = $_SESSION['captcha_number1'] + $_SESSION['captcha_number2'];
    ?>
    <p>
        <label for="math_captcha"><?php echo $_SESSION['captcha_number1'] . " + " . $_SESSION['captcha_number2']; ?> = ?</label>
        <input type="text" name="math_captcha" id="math_captcha" class="input" value="" size="20" autocomplete="off" required />
    </p>
    <script type="text/javascript">
        document.addEventListener('DOMContentLoaded', function () {
            var submitButton = document.getElementById('wp-submit');
            var captchaInput = document.getElementById('math_captcha');
            submitButton.disabled = true; // Disable submit button initially

            // Function to check if the captcha is solved correctly
            function validateCaptcha() {
                var userCaptcha = parseInt(captchaInput.value.trim());
                var correctCaptcha = <?php echo json_encode($sum); ?>;
                submitButton.disabled = isNaN(userCaptcha) || userCaptcha !== correctCaptcha;
            }

            captchaInput.addEventListener('input', validateCaptcha);
        });
    </script>
    <?php
}

function validate_login_captcha($user, $password) {
    if (isset($_POST['math_captcha'], $_SESSION['captcha_number1'], $_SESSION['captcha_number2'])) {
        $user_captcha_response = trim($_POST['math_captcha']);
        $correct_answer = $_SESSION['captcha_number1'] + $_SESSION['captcha_number2'];
        
        // If the captcha is incorrect or empty, block the login and show an error
        if (empty($user_captcha_response) || (int)$user_captcha_response !== $correct_answer) {
            return new WP_Error('captcha_error', __("<strong>ERROR</strong>: Incorrect or empty math captcha.", "my_textdomain"));
        }
    }
    return $user;
}

add_action('login_form', 'add_login_math_captcha');
add_filter('authenticate', 'validate_login_captcha', 10, 3);  // Adjusted the priority to 10

Leave the first comment