Hide ReCaptcha overlay when page does not contain Contact Form 7 form.

01/30/2024
Back to Gists
<?php
/**
 * Hide Contact Form 7 reCAPTCHA on non-contact pages.
 *
 * This function removes the enqueuing of Contact Form 7's reCAPTCHA scripts
 * on pages that don't contain the Contact Form 7 shortcode. It helps optimize
 * website performance by only loading necessary scripts when needed.
 *
 * Gist Keywords: wordpress, recaptcha, cf7, contact gorm 7, performance
 *
 * @author Knol Aust
 * @version 1.0.0
 * @link https://knolaust.com
 */

add_action( 'wp_enqueue_scripts', 'knolaust_hide_cf7_recaptcha', 1 );

function knolaust_hide_cf7_recaptcha() {
	global $post;

	if ( isset( $post ) && is_singular() && has_shortcode( $post->post_content, 'contact-form-7' ) ) {
		return;
	}

	remove_action( 'wp_enqueue_scripts', 'wpcf7_do_enqueue_scripts' );
	remove_action( 'wp_enqueue_scripts', 'wpcf7_recaptcha_enqueue_scripts' );
}
?>