Shoora
10/3/2018 - 4:46 AM

Contact Form 7 plugin: Load Javascript and CSS on Pages, Posts and CPTs where Contact Form 7 shortcode is used.

Contact Form 7 plugin: Load Javascript and CSS on Pages, Posts and CPTs where Contact Form 7 shortcode is used.

<?php
// Unload CF7 assests
add_filter( 'wpcf7_load_js', '__return_false' );
add_filter( 'wpcf7_load_css', '__return_false' );


add_action( 'the_content', 'load_cf7_assets' );
function load_cf7_assets($content){
	global $post;
	
	// Load assests when content contains CF7 shortcode.
	$post_content = $post->post_content;
	if ( has_shortcode( $post_content, 'contact-form-7' ) ) { // Check if content contains CF7 shortcode
		// Load CF7 Javascript
		if ( function_exists( 'wpcf7_enqueue_scripts' ) ) {
			wpcf7_enqueue_scripts();
		}
		
		// Load CF7 CSS
		if ( function_exists( 'wpcf7_enqueue_styles' ) ) {
			wpcf7_enqueue_styles();
		}
	}
	
	return $content;
}
?>