I’d like to cause a plugin to restrict its loading of CSS stylesheets and JavaScript JS files to only those pages for which they are needed.
An example for my question is the plugin Contact Form 7 which I’ve used to create a form in one page on my site (the “contact me” page). However it adds the following lines to EVERY page/post on the website:
<link rel='stylesheet' id='contact-form-7-css' href='http://www.r-statistics.com/wp-content/plugins/contact-form-7/styles.css?ver=2.3.1' type='text/css' media='all' />
<script type='text/javascript' src='http://www.r-statistics.com/wp-content/plugins/contact-form-7/scripts.js?ver=2.3.1'></script>
This makes me suspect that this plugin is impairing my site’s loading time, for an extension that interests me on only one page on the site.
Thus, my question is how can I remove these extra lines from all the pages except for the “Contact Me” page but without deactivating the plugin?
Styles and scripts are always set up by the functions
wp_enqueue_script()
andwp_enqueue_style()
, which have to be tied to a particular action hook in order to function. I took a peek inside Contact Form 7, and it looks like it’s using action tags ofwpcf7_enqueue_scripts
andwpcf7_enqueue_styles
to add them to thewp_print_scripts
andwp_print_styles
hooks.So, what you need to do is un-hook the scripts and styles from every page but your contact page. The
wp_head
action fires before the script and styles actions, so you’ll need to add something like this to your theme’s functions.php file:The is_page() function will return
true
when you’re on the contact page (assuming the name is “contact me”) … you can also use the page slug and page ID for the filter. On all other pages, theif()
conditional will add the script/style removal function to thewp_head
action, which fires just before thewp_print_scripts
andwp_print_styles
actions.This should remove the extra code from your pages, and you won’t have to deactivate the plug-in or edit any core files. The functions and code I’ve listed above also won’t cause your theme to break if you remove Contact Form 7 in the future, either … so no need to worry about future upgrade compatibility.