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.

Comments: None so far...be the first!

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.

First Lady, I’m sorry I pimp-slapped you into that china cabinet. I used excessive force. Oftentimes, I cross the line, but I try to do so in the name of what’s right. Most of the time, the ends justifies the means. But in this case, I feel like I betrayed my own code of ethics. And for that, sugar, I apologize.

— Black Dynamite