1

Contact form 7 is loading reCaptcha v3 scripts on all the pages of the sites which is making the website slow.
So I was using the script below which was working fine before two weeks from now, but now it stopped working and it's now loading even more scripts. Why could it be?

I don't want to use extra plugins.

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 );
2

I'd put the dequeue statements inside the 'if', replacing the $loadscripts line. No need to set the flag and then check the flag to dequeue. That might simplify the code for further debugging.

Edited: suggested code corrections:

function contactform_dequeue_scripts() {
    if (is_singular()) {
        $post = get_post();
        if (has_shortcode($post->post_content, 'contact-form-7')) {
            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);

This only dequeue's scripts if there is a shortcode for CF7, and if it is a singular page. Otherwise, things are done normally. Easier to read the code and figure out what is happening.

2
  • Hi Rick, we should vote to close and not answer if a question doesn't belong here. Anyhow, feel free to revert the edit. Q&A were useful for me, thanks all! – brasofilo Apr 2 at 16:59
  • Probably, but I see no issue in reminding people that there are better places for asking questions about WP plugins, even if that reminder is part of the answer. I don't think that that reminder should be removed from an answer, so do not agree with your edit. – Rick Hellewell Apr 3 at 19:49
1

This works for me.

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_script( 'wpcf7-recaptcha' );     
        wp_dequeue_style( 'wpcf7-recaptcha' );
        wp_dequeue_style( 'contact-form-7' );
        
    }

}
add_action( 'wp_enqueue_scripts', 'contactform_dequeue_scripts', 99 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.