MMPL1
MMPL1

Reputation: 543

How to load CF7 CSS & JS only when form is on the page

I want to speed up my site. I want to load Contact form 7 css & js only when form is one the page. I found solutions for this but they are not 100% for me. Why? Because they are based on which page I am. I want to make it another way. I'm using gutenberg to create my site and I don't know where the form will be. I could be on Contact page, on main page or on subpage in future. So my idea is load css & js only when the form is in page. Any page. So is it any way to do it? I was thinking about simple ACF Checkbox to do it. When user want to put CF7 shortcode/form he need to click checkbox for example Website have form. Maybe there's more elegant way?

Upvotes: 0

Views: 1131

Answers (2)

thinkjarvis
thinkjarvis

Reputation: 11

I cannot get the script in the previous answer to work.

However the following works:

function contactform7_dequeue_scripts() {
    $check_cf7 = false;

    if( is_page('contact') ) {
        $check_cf7 = true;
    }

    if( !$check_cf7 ) {
        wp_dequeue_script( 'contact-form-7' );
        wp_dequeue_style( 'contact-form-7' );
        wp_dequeue_script( 'cf7-conditional-fields' );
        wp_dequeue_style( 'cf7-conditional-fields' );
    }
}
add_action( 'wp_enqueue_scripts', 'contactform7_dequeue_scripts', 77 );

Upvotes: 0

Howard E
Howard E

Reputation: 5639

You can simply dequeue all of the Contact Form 7 Scripts and then check for the shortocde.

Add this to your functions.php from your theme:

function contactform_dequeue_scripts() {
    $load_scripts = false;

    if( is_singular() ) {
        $post = get_post();

        if( has_shortcode($post->post_content, 'contact-form-7') ) {
            $load_scripts = true;
            
        }
    }

    if( ! $load_scripts ) {
        wp_dequeue_script( 'contact-form-7' );
        wp_dequeue_script('google-recaptcha');
        wp_dequeue_style( 'contact-form-7' );
    }
}
add_action( 'wp_enqueue_scripts', 'contactform_dequeue_scripts', 99 );

Upvotes: 1

Related Questions