I’m using the script tarteaucitron.js on a client’s website to manage third party cookies and scripts. The website is WordPress powered.
We have a contact form created with the ContactForm7 extension with the integrated reCAPTCHA.
I’d like to have TarteAuCitron handle the reCAPTCHA script instead of ContactForm7 loading it. I know that TarteAuCitron is able to load reCAPTCHA but I don’t know how to use it in combination with ContactForm7 settings and WordPress scripts system.
I found a way to do it. In a WordPress action hook (wp_footer
), I dequeue the reCAPTCHA script which is enqueued by Contact Form 7. I then insert a custom TarteAuCitron service and service call (different for reCAPTCHA v2 and v3), then the Contact Form 7 bootstrap script:
// remove recaptcha script
wp_dequeue_script('google-recaptcha');
// enqueue recaptcha service
// $service contains the definition script of the TarteAuCitron service named 'recaptchacf7'
wp_add_inline_script('tarteaucitron', $service, 'after');
// enqueue service call
wp_add_inline_script('tarteaucitron', '(tarteaucitron.job = tarteaucitron.job || []).push("recaptchacf7");', 'after');
With reCAPCHA v3, the tricky part is to retreive the Contact Form 7 bootstrap script which is not enqueued in a standard way but simply written during the wp_footer
action. We need to prevent its immediate insertion, and insert it in the service definition script for later activation if website user choses to enable it. I did this with the help of the ob_start()
and ob_get_clean()
PHP functions:
if (function_exists('wpcf7_recaptcha_onload_script')) {
array_push(wp_scripts()->done, 'google-recaptcha');
ob_start();
wpcf7_recaptcha_onload_script();
$bootstrap = preg_replace('/<\/?script[^>]*>/', '', ob_get_clean());
array_pop(wp_scripts()->done);
}
I wrapped the code in a WordPress plugin which can be found here : cf7-tac-recaptcha. It includes services definition scripts for reCAPTCHA v2 and v3. There’s nothing more to configure.