Possible to disable CSS UNLESS the shortcode exists in a page or post?

I have a very large site but only a few pages where the Gravity Forms shortcode is inserted. I tried to see if I could disable CSS in the settings but enable it dynamically in functions.php for the pages that actually had the shortcode but this doesn’t appear to be working. I’m not using forms in the footer so I thought this might be an elegant solution.

function add_gravityforms_shortcode_styles() {
    global $post;
	$gforms_path = 'https://mysite.com/wp-content/plugins/gravityforms/legacy/css/';
	if ( has_shortcode( $post->post_content, 'gravityforms' ) ) {
        wp_enqueue_style( 'gforms_reset_css', $gforms_path);
    	wp_enqueue_style( 'gforms_datepicker_css', $gforms_path );
    	wp_enqueue_style( 'gforms_formsmain_css', $gforms_path );
    	wp_enqueue_style( 'gforms_ready_class_css', $gforms_path );
    	wp_enqueue_style( 'gforms_browsers_css', $gforms_path );
    }
}
add_action( 'wp_enqueue_scripts', 'add_gravityforms_shortcode_styles');

Any ideas or best practices? I’d rather not load 5 CSS files that add over 100kb to pages that don’t need them.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.