This is a followup to my previous post on adding scripts only to the WordPress pages that need them. Please read that first, or this might not make much sense…

To cleanup the dynamically generated head section even more, you can disable the styles associated with scripts that aren’t loaded on every page.

The easy way to do this is very similar to what I talked about last time – add this code to your functions.php file (or custom-functions.php if your theme supports it):

The plugin I’m working on is WPNG Calendar, which displays a stream of events from Google Calendar. I want to show it, in this case, only on the site’s About Us page. I’ve already deregistered the scripts associated with WPNG Calendar on most pages, so now I want to hide the styles on the same pages (why load them if you don’t need them?).

So now you’ll do the same thing as in the previous post with a twist:

  1. View the source for a page on your site and find the CSS stylesheet links associated with the plugin that you’ve already deregistered on most pages;
  2. Open up the file that calls that stylesheet – in my case I’m looking at wpng-calendar.php.
  3. Search for wp_enqueue_style within the PHP file and find the handle for the stylesheet you want to deregister. The handle is the first element in parentheses after the wp_enqueue_style element – in the snippet above they are thickbox and style.

A Problem That You Can Fix Yourself!

What happens if you can’t find a ‘wp_enqueue_style’ in your PHP file? This is unfortunate; it means that the plugin creator isn’t making easy for you. Using wp_enqueue_script and wp_enqueue_style makes it simple to work with the tools WordPress has built-in, but there’s a way around this.

Look for a link that calls a stylesheet – something like this:

Comment that line out and add your own wp_enqueue_style line, replacing the handle with the stylesheet name and editing the source link as needed (refer to this reference for parameters, I didn’t include what I wasn’t sure about):

Now you have a stylesheet being loaded in the way WP intended it to happen and you have a handle (‘style’) that you can plug into the deregister function.

Do the same thing for any other stylesheets being called, add those handles to the function and you should be good to go. This is the final version of my function:

You can see that I’m hiding the styles from the head section on all but three pages:

I hope this is helpful – please let me know if you find these two posts on restricting plugin loading useful and understandable.

« »