Is it possible to change the attributes of a registered style or script before it fires?

Modify a registered style’s path

I wanted to tweak the path to one of the WordPress admin stylesheets so i could keep requests down, and because it makes little sense to include two stylesheets, when the one i’m calling redefines all the styling in the stylesheet enqueued by WordPress.

The idea is basically to re-point the existing style at a different stylesheet, two hooks are appropriate

  • style_loader_src
  • style_loader_tag.

The former provides just the stylesheet URL(or path) and the handle(that’s the name the style is registered with), the latter provides the complete HTML string(and handle) for the stylesheet being included.

I decided to use style_loader_src to switch the colors stylesheet path(src) because that’s literally all i need, to adjust the path and know the current handle, so suits my needs perfectly.

Example filter that changes the path to the colors stylesheet.

Checks if the handle is the colors stylesheet, and updates the path when it is.

function switch_stylesheet_src( $src, $handle ) {
    if( 'colors' == $handle )
        $src = plugins_url( 'my-colors.css', __FILE__ );
    return $src;
}
add_filter( 'style_loader_src', 'switch_stylesheet_src', 10, 2 );

The above filter will basically take the existing colors stylesheet output, eg.

<link rel="stylesheet" id='colors-css' href="http://example.com/wp-admin/css/colors-fresh.css?ver=20100610" type="text/css" media="all" />

And convert it to..

<link rel="stylesheet" id='colors-css' href="http://example.com/wp-content/plugins/my-plugin/my-colors.css" type="text/css" media="all" />

I find this method preferable to enqueuing an additional stylesheet, it’s one less requests, and there’s far less CSS overrides required in whatever styling you’re doing, because you’re essentially hijacking that request to load your own stylesheet instead.

Leave a Comment

error code: 523