WP Rocket - WordPress Caching Plugin

Load assets of ‘Contact form 7’ on form pages only [NO PLUGIN]

contact form 7 assets

As we know, the Contact form 7 plugin is one of the leading contact form plugins for WordPress and more than 5 million users are using it.

But with its last updates, Contact form 7 is loading too many assets (stylesheets and scripts) and this affects the WordPress performance.

In this article we will try together to load `Contact form 7` assets in only pages that already has a form so those assets won’t affect the whole site’s performance.

By default, Contact form 7 is loading all assets inside all pages and the reason is as mentioned by the plugin author:

there is a technical difficulty for a plugin in knowing whether the page contains contact forms or not at the start of loading.


Load Styles/Scripts of Contact form 7 on specific pages

add_filter( 'wpcf7_load_js', 'wptip_load_contact_form7_assets' );
add_filter( 'wpcf7_load_css', 'wptip_load_contact_form7_assets' );

function wptip_load_contact_form7_assets(){
	global $post;
	$in_posts = [ 176 ];

        return in_array( $post->ID, $in_posts, true );

We can put this code directly into the functions.php file inside our active theme and it works directly, or we can create a small WordPress plugin and put this code inside it so it works but after activating this new plugin.

Code Explanation

We are using two filters from CF7 that needs to return boolean value (true or false) so with true, it will load assets otherwise with false it will not load them.

so we created an array that has the page IDs that have CF7 forms inside it and then comparing the current page ID with this array and then return true or false based on that.

How may I know the post ID for the current page?

Login as an admin and open the page you want to know its ID and from the top admin bar click Edit Page and get the ID from the opened URL.

If you are interested in making it a custom plugin, you can contact us and we will provide you the full source code for this plugin so you can enable/disable it whenever you want.

Leave a Reply

Your email address will not be published. Required fields are marked *