Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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');?>}

</style>

Is that a good practice?

share|improve this question

4 Answers 4

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.

share|improve this answer
1  
And so there are functioncs that I don't know in WP. :) +1 Off course. –  G. M. Sep 7 '13 at 6:57

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.

share|improve this answer

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...!

share|improve this answer

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:

<?php
function wpse_111373_output_plugin_css() {
    ?>
    <style type="text/css">
        .innertrow { background-color: <?php get_option('css_value'); ?>;}
    </style>
    <?php
}
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. :)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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