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.
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:
- Register a custom function with `wp_enqueue_scripts`.
- Look through the registered styles.
- 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.
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.