UPDATE – 02/23/2016
I no longer use Contact Form 7 as I have migrated to Gravity Forms, but this post will still prove helpful for those who use CF7.
Typically, I use Contact Form 7 as my form of choice simply because it is the first one I used and I am most comfortable with it. Lately, I’ve worked more with Gravity Forms. I’m a pretty big fan already – but of course most people will choose the free (CF7) over the not-free (Gravity) so this tutorial should come in handy.
The first thing you need to do is drop the following code into your functions.php file.
These filters tell your site to NOT load the js and css files from Contact Form 7. Simple enough, right?
The next step is to enqueue (or load) the files on the pages you need the contact form on. In my case I only need the contact form on my actual contact page. I don’t have a page template created specifically for my contact page since it uses the same page template as all of my other interior pages so we need a little extra code to ensure the functions only execute when we want them to.
If you have a page template specific to your contact form you simply need to drop this block of code on to that page template. Side Note: If you are working on a pre-built theme, make sure to make any template changes in a child theme to ensure updates won’t override your template changes.
<?php if ( function_exists( 'wpcf7_enqueue_scripts' ) ) : ?> <?php wpcf7_enqueue_scripts(); ?> <?php endif; ?> <?php if ( function_exists( 'wpcf7_enqueue_styles' ) ) : ?> <?php wpcf7_enqueue_styles(); ?> <?php endif; ?>
Simply put, this checks that the CF7 script and style enqueue scripts exists, and if so, it executes them. Since we only have this snippet on the page template of the contact form (or whatever you want) it will only load on that page. Now, if you have a generic page template that is used for a variety of pages, like I do on my site, you’ll want to wrap that code in an if statement to make sure it only executes on the page you want it to. In my case I dropped the following code onto my page_base.php template:
<?php if( is_page( 'contact' ) ) : ?> <?php if ( function_exists( 'wpcf7_enqueue_scripts' ) ) : ?> <?php wpcf7_enqueue_scripts(); ?> <?php endif; ?> <?php if ( function_exists( 'wpcf7_enqueue_styles' ) ) : ?> <?php wpcf7_enqueue_styles(); ?> <?php endif; ?> <?php endif; ?>
It is identical to the other block except that we are include an ‘is_page’ check for the ‘contact’ page where ‘contact’ is the page slug of the page we want to load the scripts on. You can use any combination of page checks like is_single(), is_archive(), etc…to make it load where you want it to based on the needs of your project.