Wordpress Snippets

How to Stop Loading Contact Form 7 JavaScript And CSS in WordPress

Contact form 7 is undoubtedly one of the most popular plugins in WordPress plugins directory. It makes our life a lot easier by allowing us to create contact forms without any PHP knowledge and add them in our website with the help of shortcode. The plugin is super easy to set up and use. But the only downside I could see is that it automatically inserts couple of JavaScript and CSS files on pages. Although it’s essential to have those files on page for proper functioning of Contact form 7 but it’s useless to keep plugin JavaScript and CSS files on pages that do not have any contact form.

In this topic, we will see how to remove or stop loading Contact form 7 JavaScript and CSS files. Contact form 7 use standard wp_enqueue_scripts function to load these static plugin files which makes it easy for us to stop them from loading on all WordPress pages and allow them manually, to load on pages that actually contains a contact form.

So following code snippet will disable the loading of plugin JavaScript and CSS files. You must add this code snippet into your theme’s functions.php file.

// stop loading Contact form 7 JavaScript and CSS files
add_filter( 'wpcf7_load_js', '__return_false' );
add_filter( 'wpcf7_load_css', '__return_false' );

Super easy. Right?

Now if we want to include Contact form 7 JavaScript and CSS files on a page, then we will add this code snippet.

// selectively load Contact form 7 JavaScript and CSS files
function rapidx_deregister_javascript() {
    if ( is_page( array( 'contribute', 'contact-us' ) ) ) {
        if ( function_exists( 'wpcf7_enqueue_scripts' ) ) {
            wpcf7_enqueue_scripts();
        }
        if ( function_exists( 'wpcf7_enqueue_styles' ) ) {
            wpcf7_enqueue_styles();
        }
    }
}
add_action( 'wp_enqueue_scripts', 'rapidx_deregister_javascript', 100 );

Hire Us. Or just say Hi!
Need a job? Apply to get one.