When working on a pre-existing version of a site, you may need to check if a style is already loaded. This, in and of itself, is not that difficult, but if it’s using an older version of a dependency, then it can get a little more complicated.

For example, let’s say that you’re building a plugin for an existing site. The existing site uses something like Font Awesome, but it’s using an older version.

Font Awesome

The requirements call for some updated icons that aren’t available in the existing version. Furthermore, the version of Font Awesome maybe be the minified version or not so we need to check for that.

Remove Enqueued Stylesheet

One of the challenges that comes with doing this in the context of a plugin is that you don’t know when the other styles are enqueued. As such, we have to make sure that we properly prioritize the hook.

The general process goes like this:

  1. Register a custom function with wp_enqueue_scripts.
  2. Look through the registered styles.
  3. If we find what we’re looking for, then we deregister it.

First, we need to register the function:

Then we need define the function to look for a copy of the stylesheet so that we can unregister it:

Note that the above code takes advantage of wp_list_pluck which is a useful function when dealing with lists.

From the Codex:

Pluck a certain field out of each object in a list

It’s a simple function, but really useful in situations like this. Be sure to check it out if you’ve not used it before.

Finally, remember that when you’re ready to enqueue your own asset, the priority for the call needs to be after the one for deregistering the previous version of the asset.

It’s Not About Font Awesome

To be clear, this post is not about Font Awesome. That just happened to be the example used. Instead, it’s about how to remove existing, registered style.

Remember to be careful when doing this: Make sure that you’ve properly prioritized your hooks. Otherwise, you may end up with unintended consequences or non-functioning code.


Join the conversation! 1 Comment

  1. It’s weird when plugin like scroll-to-top-button adds the whole font-awesome css file to display only 1 icon, isn’t it? (e.g. “Scroll Back To Top” plugin)

Leave a Reply