Contact Form 7 – Scripts, styles and reCaptcha only on certain pages

Many people are using the WordPress Plugin „Contact Form 7“ for displaying and managing their contact forms. The plugin is definitely a musthave if you have no idea, how to integrate a contact form into your WordPress blog. As a contact form is one of the many used ways to flood your inbox with spam mails, the plugin also integrates the Google reCaptcha Service to prevent you from being bombed by spam mails. The plugin author changed the integration to version 3 some time ago which lead to the problem, that the little reCaptcha overlay is displayed on every page of your blog. Some people will find that okay but in my opinion, this should be fixed. After I did some research in the plugin’s forum on wordpress.org I found some working solutions, but there was always something missing. Either the CSS styles were loaded on every page or you had to define the ids of the pages, on which the assets of the plugin had to be loaded.

I came up with the following solution. The scripts, styles and the reCaptcha assets are only loaded on pages, on which the WordPress shortcode „contact-form-7“ is found. The snippet has to be placed in the „functions.php“ file of your theme.

function manage_cf7_js_styles_recaptcha() {
	// Dequeue cf7 and recaptcha scripts and styles, preventing them from loading everywhere
	wp_dequeue_script( 'contact-form-7' );
	wp_dequeue_script( 'google-recaptcha' );
	wp_dequeue_style( 'contact-form-7' );

	// If current post has cf7 shortcode, enqueue!
	global $post;
	if ( isset( $post->post_content ) AND has_shortcode( $post->post_content, 'contact-form-7' ) ) {
        if ( function_exists( 'wpcf7_do_enqueue_scripts' ) ) {
            wpcf7_do_enqueue_scripts();
            wp_enqueue_script( 'google-recaptcha' );
        }
    }
}

add_action( 'wp_enqueue_scripts', 'manage_cf7_js_styles_recaptcha', 10, 0 );

First of all, the scripts and styles of Contact Form 7 are dequeued and also the Google reCaptcha script is removed. After that, it is checked if we have a post with content and if the content includes the shortcode „contact-form-7“. Only then, the „wpcf7_do_enqueue_scripts“ function is fired, which includes the scripts and styles for Contact Form 7 and additionally the Google reCaptcha script is enqueued again.