17 February 2025

How to add re-captcha v3 on all Elementor forms using coding?

 Add re-captcha v3 on all Elementor forms using coding


add_action('wp_footer',function(){

    ?>


<script src="https://www.google.com/recaptcha/api.js?render=6LfBtdkqAAAAAMTW5EedKrwh_yuGGNEbp5B-g96i"></script>

<script>


function addRecaptchaTokenToForms() {

    grecaptcha.ready(function () {

        grecaptcha.execute('6LfBtdkqAAAAAMTW5EedKrwh_yuGGNEbp5B-g96i', { action: 'elementor_form' }).then(function (token) {

            document.querySelectorAll('form').forEach(function (form) {

                let recaptchaInput = form.querySelector('input[name="recaptcha_token"]');

                if (!recaptchaInput) {

                    // If the hidden input doesn't exist, create it

                    recaptchaInput = document.createElement('input');

                    recaptchaInput.type = 'hidden';

                    recaptchaInput.name = 'recaptcha_token';

                    form.appendChild(recaptchaInput);

                }

                // Update the token value

                recaptchaInput.value = token;

            });

        });

    });

}


// Update reCAPTCHA token on form submission

function handleFormSubmission() {

    document.querySelectorAll('form').forEach(function (form) {

        form.addEventListener('submit', function (event) {

            event.preventDefault(); // Prevent default submission to ensure token is updated

            grecaptcha.ready(function () {

                grecaptcha.execute('6LfBtdkqAAAAAMTW5EedKrwh_yuGGNEbp5B-g96i', { action: 'elementor_form' }).then(function (token) {

                    let recaptchaInput = form.querySelector('input[name="recaptcha_token"]');

                    if (!recaptchaInput) {

                        recaptchaInput = document.createElement('input');

                        recaptchaInput.type = 'hidden';

                        recaptchaInput.name = 'recaptcha_token';

                        form.appendChild(recaptchaInput);

                    }

                    recaptchaInput.value = token;

                   

                });

            });

        });

    });

}


// Initial call when the page loads

addRecaptchaTokenToForms();

handleFormSubmission();


// Reattach reCAPTCHA token and submission handler when Elementor forms reload via AJAX

document.addEventListener('DOMContentLoaded', function () {

    document.body.addEventListener('DOMNodeInserted', function (event) {

        if (event.target.classList && event.target.classList.contains('elementor-widget-form')) {

            addRecaptchaTokenToForms();

            handleFormSubmission();

        }

    });

});


</script>

<style>

.grecaptcha-badge{

    display: none !important;

}

</style>

<?php

 });



/* add_action('elementor_pro/forms/new_record', function($record, $handler) { */

add_action('elementor_pro/forms/validation', function($record, $handler) {

    

    // Ensure this is the form you want to validate

    $form_name = $record->get_form_settings('form_name');

    /* Uncomment this if you want to target a specific form

    if ('your_form_name' !== $form_name) {

        return;

    }

    */


    $raw_fields = $record->get('fields');

    $fields = [];

    foreach ($raw_fields as $id => $field) {

        $fields[$id] = $field['value'];

    }


    // Get the reCAPTCHA token from the hidden field

    $recaptcha_token = isset($_POST['recaptcha_token']) ? sanitize_text_field($_POST['recaptcha_token']) : '';


    $recaptcha_secret = '6LfBtdkqAAAAAEZhOEScydwXVGauTNUxCWO0b2pi'; // Replace with your reCAPTCHA secret key


    // Verify the reCAPTCHA response

    $response = wp_remote_post('https://www.google.com/recaptcha/api/siteverify', [

        'body' => [

            'secret'   => $recaptcha_secret,

            'response' => $recaptcha_token,

            'remoteip' => $_SERVER['REMOTE_ADDR'], // Optional

        ],

    ]);


    $response_body = wp_remote_retrieve_body($response);

    $result = json_decode($response_body, true);


    if (empty($result['success']) || $result['score'] < 0.5) {

        // Stop the form submission if validation fails

        $handler->add_error_message('reCAPTCHA validation failed. Please try again.');

        $handler->add_error('recaptcha_token', 'Please verify you are not a robot.');


        // Stop further actions (e.g., saving data or sending email)

        $handler->add_response_data('success', false);


        return false; // Exit the hook early

    }


    // If validation passes, continue with normal form processing

}, 10, 2);

No comments:

Post a Comment

How to add re-captcha v3 on all Elementor forms using coding?

 Add re-captcha v3 on all Elementor forms using coding add_action('wp_footer',function(){     ?> <script src="https://www...