How to dequeue a stylesheet by src, not handle?

The question:

I’m trying to develop a WordPress plugin that will dequeue/deregister Font Awesome stylesheets added to a theme by certain plugins that users may install, if the theme already make use of Font Awesome.

In other words: if an administrator uses a theme that has Font Awesome font-awesome.css (or font-awesome.min.css) and he uses 2 plugins that make use of Font Awesome too, the administrator will ended up with 3 font-awesome.css (or font-awesome.min.css) stylesheets loaded.

Is there a way to check if the Font Awesome stylesheet is already loaded by the theme and if so, automatically dequeue/deregister all plugins Font Awesome stylesheets, before the theme enqueue it?

The solution I have in mind is something like this (pseudo code):

add_action( 'wp_enqueue_scripts', 'no_more_fontawesome', 999 );
function no_more_fontawesome() {
    if ( src_contain ('font-awesome.css') || src_contain('font-awesome.min.css') ) {
        wp_dequeue_style( that has font-awesome.css or font-awesome.min.css in src);
    }

A solution might be a regex check in src for the expressions font-awesome.css and font-awesome.min.css but how to achieve this?

Any help will be greatly appreciated!

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

I think you are talking about a rare scenario. “font-awsome” is the expected name that all plugins and themes should be using as handle. If the developer has not changed the source code of font awsome CSS file, there is no reason to change the name of the handle. Anyway, you can check the global $wp_styles object and make a regex in the src value of each enqueued style:

function cybmeta_dequeue_fontawsome() {

    global $wp_styles;
    // we use preg_match to find only the following patterns as exact matches, to prevent other stylesheets that contain font-awesome expression to be also dequeued
    $patterns = array(
        'font-awesome.css',
        'font-awesome.min.css'
        );

    $regex = '/(' .implode('|', $patterns) .')/i';

    foreach( $wp_styles -> registered as $registered ) {

        if( preg_match( $regex, $registered->src) ) {
            wp_dequeue_style( $registered->handle );
            // FA was dequeued, so here we need to enqueue it again from the location we want (cdn in our code)
            wp_enqueue_style( 'font-awesome', '//netdna.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css' );
        }
    }

}
add_action( 'wp_enqueue_scripts', 'cybmeta_dequeue_fontawsome' );


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment