Stop Contact Form 7 & reCaptcha JS/CSS From Loading On Every Page

Contact Form 7 is a WordPress plugin that allows you to add forms to pages. A downside to using it is that out of the box it adds the Contact Form 7 JavaScript and CSS to every page even if there is no contact form there. It does the same with the reCaptcha assets if you have that enabled. This results in unnecessary page bloat and adds the reCaptcha badge to the bottom right corner of every page. This is the code I have used to hide it:

/**
 * Dequeue the Contact Form 7 and reCaptcha assets on pages without a contact form.
 */
function restrict_contactform7_assets() {
    // Add/edit the page numbers to match your site.
    if(!is_page(10) && !is_page(240)) {
       wp_dequeue_script('contact-form-7');
       wp_dequeue_script('google-recaptcha');
       wp_dequeue_script('wpcf7-recaptcha');
       wp_dequeue_style('contact-form-7');
    }
}
add_action( 'wp_enqueue_scripts', 'restrict_contactform7_assets' );

You can get the page id number from the address bar when you open it for editing in the admin.

Share Article

Comments: 1

Leave a reply

Please fill in the form fields and improve Skynet by completing the captcha!

Thank you! All comments are moderated so yours will appear shortly.
  • Cobra
    Cobra

    Thanks for this, it works great.

    And… the is_page function also accepts a page title like ‘Contact Us’ or a slug like ‘contact-us’ so you don’t need to look up the ID.

    I’m using this code in a plugin so had to change the hook from ‘wp_enqueue_scripts’ to ‘wp_print_scripts’

We are not here to determine innocence of guilt, that time has passed.
We are not here for justice or to save the millions that you have tainted.
We are here to reward you.
We are the consequences of your actions.
We are its hand and its kindly edge
…and we have come for you.

— Chief Librarian Fel Zharost of the Night Lords Legion, Child of Night