Loading WordPress Contact Form 7 Javascript and Styling Only when Necessary

The Contact Form 7 plugin seems to be the best available plugin of it’s kind. Robust, flexible and infinitely customisable. It appears on most of my WordPress installs along with Flamingo and sometimes Really Simple CAPTCHA.

Unfortunately, one annoyance is that In it’s default settings, Contact Form 7 loads its JavaScript and CSS stylesheet on every page. Here’s how I fixed this so it only loads when necessary.

1 –  Stop loading the JavaScript and CSS stylesheet on all pages

Add the following to your wp-config.php

define('WPCF7_LOAD_JS', false);
define('WPCF7_LOAD_CSS', false);

 

Of course, you can choose either JS or CSS, or of course, both.

2 – Load the JS and CSS on pages that contain forms. 
I’m aware there are plenty of methods to achieve this, such as page templates. I prefer my method as it is more flexible and doesn’t rely on page templates.
Add the following to your functions.php

function load_my_scripts() {
	if (is_page('contact')) {
		if ( function_exists( 'wpcf7_enqueue_scripts' ) ) {
			wpcf7_enqueue_scripts();
//			wpcf7_enqueue_styles();
		}
	}
}
add_action('wp_enqueue_scripts', 'load_my_scripts');

 

If you already have a hook into wp_enqueue_scripts, you could extend that existing function.

In this particular example I still don’t load the default styles, as I prefer to create my own to suit the existing site design. However you can easily load the default styles by uncommenting that line.

Author: Kieran Barnes

Kieran is a PHP developer with 15 years commercial experience. Specialist in WordPress, CakePHP, CubeCart and all things PHP.

Leave a Reply

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