This CSS Stuffing Works, But Is This A Good Practice?

I am trying to include a dynamic css in my plugin, I have been searching anywhere but doesn’t find any case that is similar to what I do. And what I use to do it is by adding a css file directly into the end of my plugin php file after the closing php tag ?> without adding any other stuffs like calling wp head etc.

Here is the example of the code I put directly into the end of my plugin’s file:

<style type="text/css">

   .innertrow { background-color: <?php get_options('css_value');?>}


Is that a good practice?

Solutions Collecting From Web of "This CSS Stuffing Works, But Is This A Good Practice?"

You can use wp_add_inline_style() to add to a stylesheet that you’ve already defined, such as in your plugin. This way an options screen or other user settings can affect the final style output.

That could become very tedious, however, depending on how many changes you are giving the user the power over. However, it is the “best practice” as far as I know.

Of course it is not a good practice, since it will be considered as plugin error by WordPress. It will output an error message on plugin activation like this:

The plugin generated xxx characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.

Where the xxx is the amount of the codes + spaces you put after the ?> tag. It is just the same as locating space/s or unaccepted codes before the first <?php tag in your main plugin and or after it.

I believe it’s possible to dynamically write a CSS file using PHP, but you’d have to find out more on it, I don’t know much about it myself. I’m planning on doing it soon, as I noticed people putting a LOT of CSS in the on a theme I was working on. It’s bad practice in many ways, so best to avoid where possible. Sadly there are only 24hrs in a day…!

If you need to add dynamic CSS and don’t have a stylesheet already added that you want to append it to, you can hook in and output it in the wp_head action hook:

function wpse_111373_output_plugin_css() {
    <style type="text/css">
        .innertrow { background-color: <?php get_option('css_value'); ?>;}
add_action( 'wp_head', 'wpse_111373_output_plugin_css' );

Don’t just add the CSS to the end of your plugin file. However, as far as this being a “best practice” I don’t know. 🙂