Selectively enqueue Contact Form 7 plugin assets.
<?php
/**
* Selectively enqueue Contact Form 7 plugin assets.
* Disables global CF7 loading; enqueues only when a form is detected.
* Checks singular post content only; does not detect forms in widgets or sidebars.
*/
if (class_exists('WPCF7')) {
add_filter('wpcf7_load_js', '__return_false');
add_filter('wpcf7_load_css', '__return_false');
add_action('wp_enqueue_scripts', function() {
if (!is_singular()) {
return;
}
$post = get_post();
if (!$post) {
return;
}
$has_form = has_shortcode($post->post_content, 'contact-form-7')
|| (function_exists('has_block') && has_block('contact-form-7/contact-form-selector', $post))
|| !empty(get_post_meta($post->ID, 'contact_form', true));
if ($has_form) {
if (function_exists('wpcf7_enqueue_scripts')) {
wpcf7_enqueue_scripts();
}
if (function_exists('wpcf7_enqueue_styles')) {
wpcf7_enqueue_styles();
}
}
});
}
?>
functions.php