0

Is it possible to perform str_replace inside an enqueue stylesheet? i can do str_replace on inline style with this function

function replace_text($text) {
    $text = str_replace('background-image', 'background', $text);
    return $text;
}
add_filter('the_content', 'replace_text');

is it possible to perform the same action inside style.css file ? wp-content/plugins/assets/style.css

1
  • 3
    what problem are you trying to solve by doing this? Can you provide some context? It's a highly unusual request and not the normal step for fixing a CSS issue or overriding plugin CSS
    – Tom J Nowell
    May 30, 2022 at 13:33

1 Answer 1

1

No, because the CSS file isn't loaded in and parsed by PHP—it's just "printed" to the browser at the appropriate time.

You can, however, add inline styles to an enqueued stylesheet, which you would then be able to manipulate with filters.

In the code snippet below, let's assume you're using wp-content/plugins/my-plugin/assets/style.css.

add_action( 'wp_enqueue_scripts', 'wpse406238_inline_css' );
function wpse406238_inline_css() {
    // Define any dependencies here.
    $dependencies = array();
    // Set your version number here.
    $version = '1.0.0';
    // Define the media for the stylesheet here.
    $media = 'all';
    wp_enqueue_style( 'my-handle', plugins_url( '/assets/style.css', __FILE__ ), $dependencies, $version, $media );

    // Add some inline CSS.
    $inline_css = 'h1 { color: #000; }';
    // Filter that inline CSS, so others can change it as needed.
    $inline_css = apply_filters( 'my_plugin_inline_css', $inline_css );
    // Add the CSS to the rendered page.
    wp_add_inline_style( 'my-handle', $inline_css ); 

}

// ...elsewhere...
add_filter( 'my_plugin_inline_css', 'wpse_406238_filter_my_css' );
function wpse_406238_filter_my_css( $css ) {
    // Green is the new black.
    $css = str_replace( '#000', '#0f0', $css );
    return $css;
}

References

Not the answer you're looking for? Browse other questions tagged or ask your own question.