Load the Contact Form 7 Stylesheet and JavaScript Only When Necessary (the Right Way)

Contact Form 7,Development,Snippets,Troubleshooting,WordPress,WordPress Filters

If you want to keep your WordPress project lean and you share my affinity for using Contact Form 7 on simple forms, then you definitely want to make sure you load the Contact Form 7 stylesheet and JavaScript only when necessary. The right way. Let me begin by demonstrating the wrong way, because I believe this method may still prevail due to the brief tutorial offered by the plugin developer himself.

The Old Way

Takayuki Miyoshi is the plugin’s developer and he’s done a great job creating a ubiquitous solution to a common headache. Unfortunately, the advice on his site stopped working for me, which is just fine because it was inappropriate anyway. He recommends setting two constants in your wp-config.php file:

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

Then we’re left in the precarious position of enqueueing them at some later time—but before wp_head()—with this:

if(function_exists('wpcf7_enqueue_scripts')) {
  wpcf7_enqueue_scripts();
  wpcf7_enqueue_styles();
}

The Problem

Since I use the Roots theme, this leaves me with two choices: dirty up my head.php or place it atop my base.php. If I choose the latter, I need to remember that if I override base.php then the override may need that function too.

As I mentioned, this approach actually stopped working for me altogether. The latest version of Contact Form 7 may break this enhancement because I tried it on several default WordPress themes and it also failed.

But the most significant issue for me is that I do not include wp-config.php in my WordPress Git repositories (and you shouldn’t either), mainly because my credentials change between my local dev environment and my staging/production environments. If I’m using Roots’s Bedrock stack then this solution is workable because I can define constants for each of my stages, but I suspect that many developers may be using Git in a more straightforward project structure.

The Right Way

I think the cleanest way to implement this is to leave wp-config.php alone. Seriously, don’t touch it. Then open up the template file that contains your theme’s call to wp_head() and add this action hook immediately above wp_head():

No need to use the exact tag, just ensure it does not conflict with another tag. Then use the new Contact Form 7 filters to remove the styles as needed in your theme functions file (typically functions.php), like so:

When the if() statement evaluates to true then Contact Form 7 styles and JavaScript will be enqueued as usual; otherwise they will not. You can add any of your conditional checks right there and not worry about touching wp-config.php.

This is the right way to load the Contact Form 7 stylesheet and JavaScript when you need it.


Leave a Comment