The WordPress Contact Form 7 plugin loads its scripts into every page and post by default. Wouldn’t it be nice to have a way to specifically enqueue the CF7 scripts for selected pages and posts? This tutorial will show you how to manually enqueue or load Contact Form 7 scripts for a WordPress website.
What is Contact Form 7?
CF7 is a free WordPress contact form plugin. It allows the creation and management of multiple forms that can be easily added to a WordPress website. It is one of the oldest contact form plugins in the WordPress plugin repository and has received over 5+ million downloads. The plugin author regularly updates the plugin and it has an active support forum. Because of the popularity and widespread use of Contact Form 7, if you have designed or developed WordPress websites, you have probably used CF7 at one point.
An unfortunate downside to Contact Form 7 scripts is that they are bulky and load into every part of a WordPress website. This is not ideal when optimizing a website to improve speed and performance for better user experience. Consequently, the plugin doesn’t offer a way to select which pages or posts will load the CF7 scripts. This is why a customized solution is necessary.
How to Manually Enqueue Contact Form 7 Scripts for Specific Pages and Posts
The following PHP code snippet dequeues the JS and CSS that is loaded by CF7. It then uses the wp_enqueue_scripts WordPress hook to enqueue the scripts for the selected pages and posts.
First, copy and paste the code snippet into the functions.php file of your active parent theme or child theme.
Finally, change the page slugs starting at line 10, stored in the array, to include the pages that you want to have the Contact Form 7 scripts enqueued. Do the same for the post slugs starting at line 14.
NOTE: The slug is the part of a URL which identifies a particular page on a website in a form readable by users.
WordPress websites can get bloated and begin to slow down. Using the PHP code snippet in this tutorial will improve the speed and performance of a website. This is done by ensuring that the Contact Form 7 scripts are loaded only when necessary.
Need help? Our WordPress Development Service is a comprehensive solution for small, medium and enterprise-level businesses. Call us at 602-633-4758 for a free consultation.