Contact Form 7 is a great form plugin for WordPress, but it loads its Javascript and CSS on every page on your site, even when you don’t have a form there. Let’s fix that by loading the scripts and styles only on the pages that need them.
Add the following code to your theme (functions.php) or [gs plugin] to load the [gs script]s and styles only on pages that have a [gs form].
< ?php
/**
* Contact Form 7
* Prevent the javascript and styles from loading on every page
* Load them only on the Contact page
*/
/* Removes the Contact Form 7 scripts and styles from all pages */
remove_action( 'wp_enqueue_scripts', 'wpcf7_enqueue_scripts' ); // Prevents the scripts from loading on all pages
remove_action( 'wp_enqueue_scripts', 'wpcf7_enqueue_styles' ); // Prevents the styles from loading on all pages
/* Adds the Contact Form 7 scripts and styles to the appropriate pages */
add_action( 'wp_enqueue_scripts', 'new_cf7_loader' ); // Loads the scripts and styles on the appropriate page(s)
/* Load the Contact Form 7 scripts and styles on the appropriate pages */ function new_cf7_loader() {
if ( is_page( array( '', 'another page' ) ) ) { // Add all pages here that contain the form
wp_enqueue_style( '-form-7', wpcf7_plugin_url( 'styles.css' ), array(), WPCF7_VERSION, 'all' );
wp_enqueue_script( 'cf7.jquery.form.js', wpcf7_plugin_url( 'jquery.form.js' ), array(), WPCF7_VERSION, true );
wp_enqueue_script( 'cf7.scripts.js', wpcf7_plugin_url( 'scripts.js' ), array(), WPCF7_VERSION, true );
}
}
?>
For the newer version of Contact Form 7 (3.3.2)
- (by HeelpBook Staff)
< ?php
/**
* Contact Form 7
* Prevent the javascript and styles from loading on every page
* Load them only on the Contact page
*/
/* Removes the Contact Form 7 scripts and styles from all pages */
remove_action( 'wp_enqueue_scripts', 'wpcf7_enqueue_scripts' ); // Prevents the scripts from loading on all pages
remove_action( 'wp_enqueue_scripts', 'wpcf7_enqueue_styles' ); // Prevents the styles from loading on all pages
/* Adds the Contact Form 7 scripts and styles to the appropriate pages */
add_action( 'wp_enqueue_scripts', 'new_cf7_loader' ); // Loads the scripts and styles on the appropriate page(s)
/* Load the Contact Form 7 scripts and styles on the appropriate pages */ function new_cf7_loader() {
if ( is_page( array( '', 'another page' ) ) ) { // Add all pages here that contain the form
wp_enqueue_style( '-form-7', '{yoursite}/plugins/-form-7/includes/css/styles.css', array(), WPCF7_VERSION, 'all' );
wp_enqueue_script( 'cf7.jquery.form.js', '{yoursite}/plugins/-form-7/includes/js/jquery.form.js', array(), WPCF7_VERSION, true );
wp_enqueue_script( 'cf7.scripts.js', '{yoursite}/plugins/-form-7/includes/js/scripts.js', array(), WPCF7_VERSION, true );
}
}
?>
SOURCE | LINK | LANGUAGE | ENGLISH |