Remove wp_add_inline_style

Is there a way to remove styles added with wp_add_inline_style?

I noticed if I call wp_add_inline_style multiple times, it just keeps adding style, it does not overwrite what was added before.

The plugin is adding styles:

$inline_css="#selector{
    color:red;
}";
wp_add_inline_style($style, $inline_css);

If I do this again:

$inline_css="#other-selector{
    color:blue;
}";
wp_add_inline_style($style, $inline_css);

It will just append those css, I would like to clear css before calling wp_add_inline_style again.

2 s
2

Remove styles added with wp_add_inline_style()

If we want to keep the custom-style-css but only remove the custom-style-inline-css, then we can try e.g.

add_action( 'wp_print_styles', function()
{
    // Remove previous inline style
    wp_styles()->add_data( 'custom-style', 'after', '' );    

} );

where after is data key for the inline style corresponding to the custom-style handler.

There is exists a wrapper for wp_styles()->add_data(), namely wp_style_add_data().

We could then define the helper function:

function wpse_remove_inline_style( $handler )
{
       wp_style_is( $handler, 'enqueued' ) 
    && wp_style_add_data( $handler, 'after', '' );
}

and use it like:

add_action( 'wp_print_styles', function()
{
    // Remove previous inline style
    wpse_remove_inline_style( 'custom-style' );    

} );

I’m skipping the function_exists check here.

To override the inline-style, added by another plugin, with our own:

add_action( 'wp_print_styles', function()
{
    // Remove previous inline style
    wpse_remove_inline_style( 'custom-style' );    

    // New inline style
    $custom_css = ".mycolor{
        background: {blue};
    }";
    wp_add_inline_style( 'custom-style', $custom_css );

} );

Note

The reason why it doesn’t work to override previous inline style with wp_add_inline_style() is because the WP_Style::add_inline_style() appends each incoming CSS string into an array. Internally it uses WP_Style::add_data() to store the accumulated CSS. Here we are using it to overcome the appending restriction of wp_add_inline_style().

Leave a Comment