Contact Form 7 (CF7) is one of the most popular plugin for WordPress websites that supports advanced features, AJAX and plenty of customization options, and can support multiple contact forms display. When Contact Form 7 plugin is activated, several JavaScript and StyleSheet (JS and CSS) are added to HTML code of all web pages and loaded every time without condition, even though no contact form powered by CF7 is inserted on most of the web pages of WordPress site. In fact, most WordPress websites use Contact Form 7 at only one page, i.e. Contacts or Contact Us page.
Additional JS and CSS files called by HTML is adding to requests required to make to the server. It affects the page load speed, especially when the JS and CSS files are embedded and called via method that blocks page rendering, which lowers the Google Page Speed and YSlow score, and bad for SEO especially Google search ranking. In page loading speed, every millisecond counts.
This tutorial guides on how to prevent and disable all Contact Form 7 JS and CSS files from loading on all WordPress web pages, except on the pages that inserted with contact forms built with CF7. In other words, we’re loading CF7 JS and CSS conditionally.
Step 1: Stop Loading Contact Form 7 JavaScript and CSS Stylesheet on All Pages
To do so, there are 2 methods. Choose any one of them:
- Edit wp-config.php (Editable via Appearance –> Editor and select functions.php file), and add the following lines:
define('WPCF7_LOAD_JS', false); // Remove CF7 JavaScript define('WPCF7_LOAD_CSS', false); // Remove CF7 CSS
- Edit the active theme’s functions.php, and add the following lines:
add_filter( 'wpcf7_load_js', '__return_false' ); // Disable CF7 JavaScript add_filter( 'wpcf7_load_css', '__return_false' ); // Disable CF7 CSS
Step 2: Add Contact Form 7 JavaScript and CSS Stylesheet to Selected Pages Only
Edit the active theme’s functions.php (Editable via Appearance –> Editor and select functions.php file) and add the following code:
add_action('wp_enqueue_scripts', 'load_wpcf7_scripts'); function load_wpcf7_scripts() { if ( is_page('contact') ) { if ( function_exists( 'wpcf7_enqueue_scripts' ) ) { wpcf7_enqueue_scripts(); } if ( function_exists( 'wpcf7_enqueue_styles' ) ) { wpcf7_enqueue_styles(); } } }
Example above assumes that the page slug for “Contact” page is “contact”. Thus, the WPCF7 scripts will only load on page that matches the page slug “contact”. If you are using a different page slug, change accordingly.
is_page( array( ‘contact’ , ‘feedback’ , ‘survey’ ) )