Speed Up Sites Which Use Contact Form 7

Remove Contact Form 7 reCaptcha JavaScript & CSS When Not Needed

When you use Contact Form 7’s reCaptcha integration, you’ll see the CSS and JavaScript assets are referenced by every page. Even pages which don’t contain a CF7 form will reference the assets. This will drag-down your page speed scores in Lighthouse and GTmetrix. By adding a little bit of code to your functions.php file, we can speed up Contact From 7 based websites.

Before we start, make sure you’re using a custom child theme so you’ve got access to your own clean functions.php file.

The Logic

The thing to do is only include the relevant files on the pages where you need them. So, we need to figure out when we actually need these assets. The simplest way of doing this is to specify the page IDs in a constant. We’ll do this at the top of our custom child theme’s functions.php file. like this:

// Page ID 123 page ID 456 both have Contact From 7 forms on them.
const HW_CF7_POST_IDS = array(123, 456);

Now all we need to do is check that Contact From 7 (CF7) is installed. If we find that it’s installed, remove the CSS and JS assets if we’re not showing a page that has one of our forms.

Let’s Write the Code

In your custom child theme’s folder, create a new file called functions-cf7.php and paste the following into it.

<?php

/**
 * Remove Contact Form 7 assets from posts/pages that don't need them.
 *
 * https://wp-tutorials.tech/optimise-wordpress/remove-contact-from-7-recaptcha-javascript-css-when-not-needed/
 *
 * Either define HW_CF7_POST_IDS as your contact form's Post ID, or set it to
 * an array of integer IDs if you've got multiple pages.
 *
 * const HW_CF7_POST_IDS = array(123); // << 123 is the post_id of your contact page.
 *
 * ...OR...
 *
 * hw_set_cf7_post_ids(123);
 */

// Block direct access.
if (!defined('WPINC')) {
	exit('Do NOT access this file directly.');
}

function hw_set_cf7_post_ids($post_id = null) {
	if (!defined('HW_CF7_POST_IDS') && !is_null($post_id) && (is_integer($post_id) || is_array($post_id))) {
		define('HW_CF7_POST_IDS', $post_id);
	}
}

// Only execute our CF7 code if Contact Form 7 is actually installed.
if (class_exists('WPCF7')) {
	function hw_cf7_get_header() {
		if (defined('HW_CF7_POST_IDS')) {
			$cf7_post_ids = HW_CF7_POST_IDS;

			$are_cf7_assets_requried = false;
			$post_id = get_the_ID();

			if (is_int($cf7_post_ids)) {
				$are_cf7_assets_requried = ($cf7_post_ids === $post_id);
			} elseif (is_array($cf7_post_ids)) {
				$are_cf7_assets_requried = in_array($post_id, $cf7_post_ids);
			} else {
				// ...
			}

			if (!$are_cf7_assets_requried) {
				add_filter('wpcf7_load_js', '__return_false');
				add_filter('wpcf7_load_css', '__return_false');
			}

			// If logged-in, there's no need for CF7 reCaptcha.
			if (!$are_cf7_assets_requried || is_user_logged_in()) {
				remove_action('wp_enqueue_scripts', 'wpcf7_recaptcha_enqueue_scripts');
			}
		} else {
			// If there's nothing in $cf7_post_ids then just lt
			// CF7 behave as it normally does.
		}
	}
	add_action('get_header', 'hw_cf7_get_header', 5);

	// Addons that make the CF7 styling a little nicer.
	function hw_wpcf7_enqueue_styles() {
		$css_file_name = 'cf7-addons.css';

		if (is_readable(trailingslashit(dirname(__FILE__)) . $css_file_name)) {
			wp_enqueue_style(
				'hw-cf7-addons-css',
				get_stylesheet_directory_uri() . '/' . $css_file_name
			);
		}
	}
	add_action('wpcf7_enqueue_styles', 'hw_wpcf7_enqueue_styles');
}

Now we just need to reference it, so add the following somewhere near the top of your custom child theme’s functions.php file

// Speed-up non-CF7 form pages.
const HW_CF7_POST_IDS = array(123, 456); // << Replace with your Page ID(s)
require_once 'functions-cf7.php';

Add some Style

If you flick through the code you’ll see that we check to see if there’s a file called cf7-addons.css. This is where we can put some CF7 refinements, like this.

/**
 * Contact Form 7 Addons
 */
.wpcf7 {
	width: 100%;
}

.wpcf7 label {
	display: block;
}

.wpcf7 input[type='text'],
.wpcf7 input[type='email'],
.wpcf7 textarea {
	display: block;
	width: 100%;
}

.wpcf7-form-control .wpcf7-list-item {
	display: table;
}

.wpcf7-form-control .wpcf7-list-item > span,
.wpcf7-form-control .wpcf7-list-item > input {
	display: table-cell;
}

/* Uncomment this if you want to hide the reCaptcha badge */
/*
.grecaptcha-badge {
	display: none;
}
*/

This file is optional – if it doesn’t exist in your custom child theme then we won’t try to load it. Also, we’ll only try and load it on pages that need the regular CF7 assets.

Test and Deploy

If you look through functions-cf7.php you’ll see there are a few tests we do before we remove the CF7 assets. Logged-in users should always have the reCaptcha removed – if someone has logged-in to your site then they should already be a valid user.

When you’re testing, you should disable any minification and page-caching plugins, so they don’t muddy-the-waters.

  1. Log out of your site and go to your contact form page. You should see the reCaptcha badge in the bottom-right.
  2. Now go to a page without a contact form… The reCaptcha badge shouldn’t be there.
  3. Finally, log in and go to the contact form page. There shouldn’t be a reCaptcha badge, because we’re logged-in.

That’s it. If you sign out of your website and go to a page without a contact form on it, you should get a better page speed score because the page isn’t having to load the reCaptcha assets. We’ve also kept this new functionality in a couple of stand-alone files (functions-cf7.php and cf7-addons.css), so we can reuse them in other WordPress projects quite easily. Perfect.

This article is based on code from the official Contact From 7 documentation.

Leave a Comment

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