0

Hi I have a problem with the optimization of the Contact Form 7 Recaptcha in WordPress, I have this code:

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

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

It suppose to retire the Recaptcha CSS on the pages that don't have a contact form, but when I Run the live site and I made a test with the forms it shows me an error message on the form, I attached the image with the message Image

I don't know if someone can help me with this please, Thank you!

1
  • your question is unclear.
    – Howard E
    Commented May 24, 2022 at 13:45

1 Answer 1

0

Try this:

    function contactform_dequeue_scripts() {
    global $post;

    if( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content,'contact-form-7') {

        wp_enqueue_script( 'contact-form-7' );
        wp_enqueue_script( 'google-recaptcha' );
        wp_enqueue_script( 'wpcf7-recaptcha' );
        wp_enqueue_style( 'contact-form-7' );
        wp_enqueue_style( 'wpcf7-recaptcha' );

    } else {
        wp_dequeue_script( 'contact-form-7' );
        wp_dequeue_script( 'google-recaptcha' );
        wp_dequeue_script( 'wpcf7-recaptcha' );
        wp_dequeue_style( 'contact-form-7' );
        wp_dequeue_style( 'wpcf7-recaptcha' );
    }  
}

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

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