Are you looking for a way to enable Contact Form 7 on specific pages only? This snippet will let you enable Contact Form 7 on certain pages only to avoid loading the plugin unnecessarily.
Instructions:
- Add this code to your theme’s functions.php file or in a site-specific plugin.
- Edit the IDs in lines 3 and 9. Currently the IDs are 8 and 10.
add_action( 'wp_print_scripts', 'deregister_cf7_javascript', 100 ); function deregister_cf7_javascript() { if ( !is_page(array(8,10)) ) { wp_deregister_script( 'contact-form-7' ); } } add_action( 'wp_print_styles', 'deregister_cf7_styles', 100 ); function deregister_cf7_styles() { if ( !is_page(array(8,10)) ) { wp_deregister_style( 'contact-form-7' ); } }
To deregister Contact Form 7’s CSS style sheet on all pages, use this snippet:
add_action( 'wp_print_styles', 'wps_deregister_styles', 100 ); function wps_deregister_styles() { wp_deregister_style( 'contact-form-7' ); }
Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.
If you liked this code snippet, please consider checking out our other articles on the site like: How to Create a Contact Form on WordPress (the Easy Way).
Do you have one for wpforms
Don’t forget to issue wp_dequeue_style( ‘contact-form-7’ ) and wp_dequeue_script( ‘contact-form-7’ ) after wp_deregister_style( ‘contact-form-7’ ) and wp_deregister_script( ‘contact-form-7’ ) respectively!
Is dequeueing really necessary after the script or style has been deregistered?
For a few years we were using this plugin on clients sites and this was very annoying. In fact it’s the main reason we stopped using it. Anyway, glad there’s now a ‘fix’ for this issue, I’m sure many people will be thankful for it
No problem glad to help,