From 6284813eeb3dd79f6e084e703f6bb1d34277e5a3 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Tue, 10 Oct 2023 12:59:04 -0700 Subject: [PATCH] Incorporate logic from contact-form-7-conditional-enqueues.php mini plugin * Use template_redirect action rather than wp to prevent accidental admin usage. * Add version check for CF7. * Add conditional enqueueing for styles in addition to scripts. * Override filters for wpcf7_load_js and wpcf7_load_css to return false. * Prevent re-enqueueing scripts after they have been enqueued. --- inc/ThirdParty/Plugins/ContactForm7.php | 47 +++++++++++++++++++++---- 1 file changed, 40 insertions(+), 7 deletions(-) diff --git a/inc/ThirdParty/Plugins/ContactForm7.php b/inc/ThirdParty/Plugins/ContactForm7.php index 773c705fa8..7a0bd4203d 100644 --- a/inc/ThirdParty/Plugins/ContactForm7.php +++ b/inc/ThirdParty/Plugins/ContactForm7.php @@ -4,25 +4,58 @@ use WP_Rocket\Event_Management\Subscriber_Interface; class ContactForm7 implements Subscriber_Interface { + + /** + * Required CF6 version. + * + * Version in which the wpcf7_shortcode_callback action was introduced. + * + * @var string + */ + const REQUIRED_CF7_VERSION = '5.8.1'; + /** * Subscribed events. */ public static function get_subscribed_events() { return [ - 'wp' => [ 'maybe_optimize_contact_form_7', 10 ], + 'template_redirect' => [ 'maybe_optimize_contact_form_7', 10 ], ]; } /** * Optimize ContactForm7 scripts. - * - * @return array */ public function maybe_optimize_contact_form_7() { - if ( defined( 'WPCF7_LOAD_JS' ) && WPCF7_LOAD_JS && ! has_action( 'wpcf7_shortcode_callback' ) ) { - // Only load the frontend scripts on the new 'wpcf7_shortcode_callback' hook. - add_filter( 'wpcf7_load_js', '__return_false' ); - add_action( 'wpcf7_shortcode_callback', 'wpcf7_enqueue_scripts' ); + // The wpcf7_shortcode_callback action was added in CF7 version 5.8.1. + if ( ! defined( 'WPCF7_VERSION' ) || version_compare( WPCF7_VERSION, self::REQUIRED_CF7_VERSION, '<' ) ) { + return; + } + + // Force scripts and styles to not load by default. + add_filter( 'wpcf7_load_js', '__return_false', PHP_INT_MAX ); + add_filter( 'wpcf7_load_css', '__return_false', PHP_INT_MAX ); + + // Conditionally enqueue scripts + add_action( 'wpcf7_shortcode_callback', [ $this, 'conditionally_enqueue_scripts' ] ); + add_action( 'wpcf7_shortcode_callback', [ $this, 'conditionally_enqueue_styles' ] ); + } + + /** + * Enqueue scripts if not already enqueued. + */ + function conditionally_enqueue_scripts() { + if ( ! did_action( 'wpcf7_enqueue_scripts' ) ) { // Prevent double-enqueueing when multiple forms present. + wpcf7_enqueue_scripts(); + } + } + + /** + * Enqueue styles if not already enqueued. + */ + function conditionally_enqueue_styles() { + if ( ! did_action( 'wpcf7_enqueue_styles' ) ) { // Prevent double-enqueueing when multiple forms present. + wpcf7_enqueue_styles(); } } }