Performance PHP Beginner

Load a Plugin’s Files Only on the Pages That Need Them

Stop plugins like Contact Form 7 loading their CSS and JavaScript on every page when they're only used on one.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 11 lines
add_action( 'wp_enqueue_scripts', function (): void {
	// Pages that actually use the plugin, by slug.
	if ( is_page( [ 'contact', 'quote' ] ) ) {
		return;
	}

	// Contact Form 7's handles. Change these for other plugins.
	wp_dequeue_style( 'contact-form-7' );
	wp_dequeue_script( 'contact-form-7' );
	wp_dequeue_script( 'swv' );
}, 100 );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

Many plugins load their files on every page “just in case”. A contact form plugin used only on your Contact page still adds CSS and JavaScript to your homepage, blog and shop. This snippet removes them everywhere except where they’re needed.

How it works

The callback runs late on wp_enqueue_scripts, after plugins have queued their files. On the pages you list it does nothing; everywhere else it dequeues the plugin’s style and scripts by handle.

Things to watch

  • Find a plugin’s handles in your page source: a stylesheet with id="contact-form-7-css" has the handle contact-form-7. The Query Monitor plugin lists them all.
  • If you add a form to another page later, add that page to the list or the form will look and behave broken.

How to test it

Open your homepage source and search for contact-form-7. It shouldn’t appear. Then check the contact page still loads the form correctly and submits.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only