By default, the popular Contact Form 7 (CF7) plugin loads it’s javascript and css stylesheet files on every page. This is unnecessary extra load on your website front-end. Those javascript and css files are only needed on the page where there is a CF7 form.
But not to worry, as there is easy way to overcome this behavior and load javascript and css files only on the pages with a CF7 form.
//remove globally
add_filter( 'wpcf7_load_js', '__return_false' );
add_filter( 'wpcf7_load_css', '__return_false' );
//enable for pages or posts or any other post types where there is a cf7 form
function careless_custom_load_contact_form_7() {
$ids = array( 23, 25, 30 );//<== declare your post/page/custom post type ids
if ( !is_page( $ids ) || !is_single( $ids ) ) {
return;
}
if ( function_exists( 'wpcf7_enqueue_scripts' ) ) {
wpcf7_enqueue_scripts();
}
if ( function_exists( 'wpcf7_enqueue_styles' ) ) {
wpcf7_enqueue_styles();
}
}
add_action("wp_enqueue_scripts", 'careless_custom_load_contact_form_7');
In the above code, we have first (line 2 and 3) removed CF7 javascript and css files from everywhere. Then on line 7, we have declared page IDs, where there is a CF7 form. Change those IDs as you need. It can be for post, page or any other custom post types.
Note that wpcf7_enqueue_scripts()
and wpcf7_enqueue_styles()
must be called before wp_head()
is called. So we have hooked it into wp_enqueue_scripts
.
Code goes in the functions.php
file of your active theme.