25% off ProSNIPC25OFF

Contact Form 7: Load Scripts and Styles Only on Form Pages

Dequeues the Contact Form 7 CSS and JavaScript on every page that does not contain a CF7 shortcode, reducing unnecessary asset loading across the site.

PHPby SnipCraft
php
<?php
if ( defined( 'WPCF7_VERSION' ) && ! function_exists( 'scseed_cf7_selective_assets' ) ) {
    /**
     * CF7 enqueues its scripts and styles on every page by default.
     * This snippet removes those assets on singular posts/pages that do not
     * contain a [contact-form-7] shortcode, and on all archive/listing pages.
     *
     * Note: does not account for CF7 blocks added via the block editor or
     * forms embedded by page-builder widgets — extend the condition below
     * to handle those cases if needed.
     */
    function scseed_cf7_selective_assets() {
        // Keep assets on any page confirmed to hold a CF7 shortcode.
        if ( is_singular() ) {
            $post = get_post();
            if ( $post && has_shortcode( $post->post_content, 'contact-form-7' ) ) {
                return;
            }
        }
        wp_dequeue_script( 'contact-form-7' );
        wp_dequeue_style( 'contact-form-7' );
    }
    // Priority 99 — run after CF7 (priority 10) has enqueued its assets.
    add_action( 'wp_enqueue_scripts', 'scseed_cf7_selective_assets', 99 );
}
#assets#contact-form-7#enqueue#forms#performance