Load Contact Form 7 Assets Only Where a Form Is Used
Keeps Contact Form 7 scripts and styles off every page except those that contain a form, removing two requests from most pages.
Opens WPIDE on
Code
// IDs of pages that show a form outside the post content (in a widget or the footer, for example).
$wpide_cf7_extra_pages = array();
add_filter( 'wpcf7_load_js', '__return_false' );
add_filter( 'wpcf7_load_css', '__return_false' );
add_action( 'wp_enqueue_scripts', function () use ( $wpide_cf7_extra_pages ) {
if ( ! function_exists( 'wpcf7_enqueue_scripts' ) ) {
return;
}
$post = get_post();
$uses = $post && is_singular() && ( has_shortcode( $post->post_content, 'contact-form-7' ) || has_block( 'contact-form-7/contact-form-selector', $post ) );
if ( $uses || ( $wpide_cf7_extra_pages && is_page( $wpide_cf7_extra_pages ) ) ) {
wpcf7_enqueue_scripts();
if ( function_exists( 'wpcf7_enqueue_styles' ) ) {
wpcf7_enqueue_styles();
}
}
}, 20 );
Notes
Does nothing unless Contact Form 7 is active.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.