Halloween Sale 15% off Ends in See the plans
PHP

Load Contact Form 7 Assets Only Where a Form Is Used

Keeps Contact Form 7 scripts and styles off every page except those that contain a form, removing two requests from most pages.

Don’t have WPIDE yet? Install it on your site

Code

// IDs of pages that show a form outside the post content (in a widget or the footer, for example).
$wpide_cf7_extra_pages = array();

add_filter( 'wpcf7_load_js', '__return_false' );
add_filter( 'wpcf7_load_css', '__return_false' );

add_action( 'wp_enqueue_scripts', function () use ( $wpide_cf7_extra_pages ) {
    if ( ! function_exists( 'wpcf7_enqueue_scripts' ) ) {
        return;
    }

    $post = get_post();
    $uses = $post && is_singular() && ( has_shortcode( $post->post_content, 'contact-form-7' ) || has_block( 'contact-form-7/contact-form-selector', $post ) );

    if ( $uses || ( $wpide_cf7_extra_pages && is_page( $wpide_cf7_extra_pages ) ) ) {
        wpcf7_enqueue_scripts();
        if ( function_exists( 'wpcf7_enqueue_styles' ) ) {
            wpcf7_enqueue_styles();
        }
    }
}, 20 );

Notes

Does nothing unless Contact Form 7 is active.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.