How to load Contact Form 7 JavaScript and styles only when necessary

By default Contact Form 7 loads its JavaScript and CSS stylesheet on every page of your website which is really not necessary.

For performance sakes, the fewer files your website has to load the better.

The following snippet, as per the official Contact Form 7 documentation, will disable Contact Form 7 scripts from all pages except your contact page.

For this, to work all you need to do is replace the page ID found on the snippet below with your own contact page ID.

To find a page ID, open your WordPress dashboard and click on Pages. Click on Edit Page and once the page has loaded, take a look at the URL in your web browser’s address bar. There you will find the page ID number displayed within the page URL e.g

The Snippet

In the code below look for is_page(1) and replace the 1 with your own page ID.

// Stop Contact Form 7 Loading Scripts On Pages
add_action( 'wp_enqueue_scripts', 'remove_cf7_scripts' );

function remove_cf7_scripts(){
   //  Remove all Contact Form 7 scripts except for the following page ID.
   if(! is_page(1) )    
      wp_dequeue_script('contact-form-7'); // Removes JavaScript File
      wp_dequeue_style('contact-form-7');  // Removes Stylesheet

Once you had added your own contact page ID simply copy and paste the snippet into your child theme’s function.php file.

If you do not have a child theme installed you could create your very own ‘snippets plugin’ by following our short guide titled, ‘How to create your own WordPress snippets plugin‘.

WordPress Maintenance from £25.99/month

Experience unparalleled WordPress support and maintenance with our exceptional service plans. Entrust us with all your WordPress needs, guaranteeing the seamless operation and upkeep of your website.

Get Started