Skip to content

Instantly share code, notes, and snippets.

@pacotole
Last active September 19, 2024 01:41
Show Gist options
  • Save pacotole/c06330e784a483130c80413a6b9da1bc to your computer and use it in GitHub Desktop.
Save pacotole/c06330e784a483130c80413a6b9da1bc to your computer and use it in GitHub Desktop.
Only enqueue Contact Form 7 scripts when there is a form in the page
/**
* Contact Form 7 only enqueue scripts when there is a form in the page
*/
// Disable contact-form-7 recaptcha enqueue action
remove_action( 'wp_enqueue_scripts', 'wpcf7_recaptcha_enqueue_scripts', 20 );
// Dequeue contact-form-7 scripts
function contact_form_7_dequeue_scripts() {
wp_dequeue_script( 'contact-form-7' );
}
add_action( 'wpcf7_enqueue_scripts', 'contact_form_7_dequeue_scripts' );
// Dequeue contact-form-7 styles
function contact_form_7_dequeue_styles() {
wp_dequeue_style( 'contact-form-7' );
wp_dequeue_style( 'contact-form-7-rtl' );
}
add_action( 'wpcf7_enqueue_styles', 'contact_form_7_dequeue_styles' );
// Trigger contact-form-7 enqueue actions when form shortcode is executed
function contact_form_7_enqueue_scripts( $out ) {
// Remove dequeue actions
remove_action( 'wpcf7_enqueue_scripts', 'contact_form_7_dequeue_scripts' );
remove_action( 'wpcf7_enqueue_styles', 'contact_form_7_dequeue_styles' );
// Enqueue contact-form-7 assets
if ( wpcf7_load_js() ) {
wpcf7_enqueue_scripts();
}
if ( wpcf7_load_css() ) {
wpcf7_enqueue_styles();
}
wpcf7_recaptcha_enqueue_scripts();
return $out;
}
add_filter( 'shortcode_atts_wpcf7', 'contact_form_7_enqueue_scripts' );
@mynameisbrendan
Copy link

Thanks for this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment