Exclude reCAPTCHA by Page

User
function v3_enqueue_recaptcha_v3() {
if (!is_admin()) {
wp_enqueue_script('google-recaptcha-v3', 'https://www.google.com/recaptcha/api.js?render=' . V3_RECAPTCHA_SITE_KEY, [], null, true);

}
}
add_action('wp_enqueue_scripts', 'v3_enqueue_recaptcha_v3');

function load_recaptcha_token_debug() {
wp_add_inline_script('google-recaptcha-v3', "
grecaptcha.ready(function() {
grecaptcha.execute('" . V3_RECAPTCHA_SITE_KEY . "', {action: 'homepage'}).then(function(token) {
console.log('reCAPTCHA Token:', token);
}).catch(function(error) {
console.error('reCAPTCHA Error:', error);
});
});
");
}
add_action('wp_footer', 'load_recaptcha_token_debug');

exclude it from particular page id

Assistant
You can modify your script to exclude the reCAPTCHA script from loading on a specific page ID by checking the current page ID using `is_page()`. Here’s how you can do it:

### Updated Code:

function v3_enqueue_recaptcha_v3() {
    // Define the page ID to exclude
    $excluded_page_id = 123; // Change this to the page ID you want to exclude

    if (!is_admin() && !is_page($excluded_page_id)) {
        wp_enqueue_script('google-recaptcha-v3', 'https://www.google.com/recaptcha/api.js?render=' . V3_RECAPTCHA_SITE_KEY, [], null, true);
    }
}
add_action('wp_enqueue_scripts', 'v3_enqueue_recaptcha_v3');

function load_recaptcha_token_debug() {
    $excluded_page_id = 123; // Same page ID as above

    if (!is_page($excluded_page_id)) {
        wp_add_inline_script('google-recaptcha-v3', "
            grecaptcha.ready(function() {
                grecaptcha.execute('" . V3_RECAPTCHA_SITE_KEY . "', {action: 'homepage'}).then(function(token) {
                    console.log('reCAPTCHA Token:', token);
                }).catch(function(error) {
                    console.error('reCAPTCHA Error:', error);
                });
            });
        ");
    }
}
add_action('wp_footer', 'load_recaptcha_token_debug');

### Explanation:
– The `$excluded_page_id` variable holds the ID of the page where you want to **prevent** reCAPTCHA from loading.
– The `is_page($excluded_page_id)` function checks if the current page matches the excluded page ID.
– If the page ID matches, `wp_enqueue_script()` and `wp_add_inline_script()` **do not execute**, preventing the script from loading.

Let me know if you need modifications! 🚀

Leave a Comment

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