Load reCaptcha Only When Needed in Contact Form 7

WordPressPosted on

Contact Form 7 is a cool tool to make forms. One thing which is always present when we work with online forms is spam. We can easily protect sites using Google’s reCaptcha.

reCaptcha is one of the best spam protection. It is integrated into CF7, so we only need to get an API key and set it up in the Contact / Integration menu.

There is one catch if you care about performance. By default, it is loading the captcha’s assets on all of the pages. It is ~10 different files and weights ~300 kb, which is a lot to load everywhere.

Fortunately, we can do this with ease!

Dequeue the Unnecessary Scripts

Always a good idea to remove the Contact Form 7 default JavaScript file load too. To do so use the following line in your functions.php:

// Remove wpcf7 script
add_filter( 'wpcf7_load_js', '__return_false' );

We also need to remove the reCaptcha loading. Use the wp_enqueue_scripts hook to dequeue google-recaptcha script.

function pine_scripts() {
    wp_dequeue_script( 'google-recaptcha' );
}

Load Scripts When Needed

For the last step, we need to load the scripts when we need them. It depends on your situation but using the wp_enqueue_scripts with custom conditions will cover the most.

Add the following snippet to the mentioned hook after the reCaptcha dequeue:

function pine_scripts() {
    if ( is_page_template( 'template-contact.php' ) ) {
        if ( function_exists( 'wpcf7_enqueue_scripts' ) ) {
            wpcf7_enqueue_scripts();
            wp_enqueue_script( 'google-recaptcha' );
        }
    }
}
add_action( 'wp_enqueue_scripts', 'pine_scripts' );

In this example, I loaded the script when the template-contact.php was in use. It was the template for my contact form. If you use wpcf7_enqueue_scripts(), it is always nice to check if it exists unless you want to break your site.

Need a web developer? Maybe we can help, get in touch!

Similar Posts

More content in WordPress category