Skip to content

Instantly share code, notes, and snippets.

@westonruter
Last active November 22, 2023 22:09
Show Gist options
  • Select an option

  • Save westonruter/af6ce5699e4b5576f51a7cd901b80152 to your computer and use it in GitHub Desktop.

Select an option

Save westonruter/af6ce5699e4b5576f51a7cd901b80152 to your computer and use it in GitHub Desktop.
<?php
/**
* Contact Form 7 Conditional Enqueues WordPress Plugin.
*
* @package OptimizeContentHeroImage
* @author Weston Ruter, Google
* @license GPL-2.0-or-later
* @copyright 2023 Google Inc.
*
* @wordpress-plugin
* Plugin Name: Contact Form 7 Conditional Enqueues
* Description: Prevent enqueueing JS and CSS for Contact Form 7 unless there is a form on the page. This is a mini plugin to implement the changes suggested in <a href="https://github.com/rocklobster-in/contact-form-7/issues/1278">contact-form-7#1278</a>.
* Plugin URI: ...
* Version: 0.1.0
* Author: Weston Ruter
* Author URI: https://weston.ruter.net/
* License: GNU General Public License v2 (or later)
* License URI: http://www.gnu.org/licenses/gpl-2.0.html
* Update URI: ...
*/
namespace CF7_Conditional_Enqueues;
add_filter( 'wpcf7_load_js', '__return_false' );
add_filter( 'wpcf7_load_css', '__return_false' );
/**
* Conditionally enqueue scripts.
*/
function conditionally_enqueue_scripts() {
if (
function_exists( 'wpcf7_enqueue_scripts' ) && // Does not exist in admin context.
! did_action( 'wpcf7_enqueue_scripts' )
) {
wpcf7_enqueue_scripts();
}
}
/**
* Conditionally enqueue styles.
*/
function conditionally_enqueue_styles() {
if (
function_exists( 'wpcf7_enqueue_styles' ) && // Does not exist in admin context.
! did_action( 'wpcf7_enqueue_styles' )
) {
wpcf7_enqueue_styles();
}
}
// Note: The wpcf7_shortcode_callback action fires in the block editor when the post data is obtained from the REST API
// via block_editor_rest_api_preload(). However, the wpcf7_enqueue_scripts() and wpcf7_enqueue_styles() functions are
// not loaded in the admin context. This necessitates the function_exists() checks.
add_action( 'wpcf7_shortcode_callback', __NAMESPACE__ . '\conditionally_enqueue_scripts' );
add_action( 'wpcf7_shortcode_callback', __NAMESPACE__ . '\conditionally_enqueue_styles' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment