How do I add CSS options to my plugin without using inline styles?

I recently released a plugin, WP Coda Slider, that uses shortcodes to add a jQuery slider to any post or page. I am adding an options page in the next version and I would like to include some CSS options but I don’t want the plugin to add the style choices as inline CSS. I want the choices to be dynamically added to the CSS file when it’s called.

I would also like to avoid using fopen or writing to a file for security issues.

Is something like this easy to accomplish or would I be better off just adding the style choices directly to the page?

5

Use wp_register_style and wp_enqueue_style to add the stylesheet. DO NOT simply add a stylesheet link to wp_head. Queuing styles allows other plugins or themes to modify the stylesheet if necessary.

Your stylesheet can be a .php file:

wp_register_style('myStyleSheet', 'my-stylesheet.php');
wp_enqueue_style( 'myStyleSheet');

my-stylesheet.php would look like this:

<?php
// We'll be outputting CSS
header('Content-type: text/css');

include('my-plugin-data.php');    
?>

body {
  background: <?php echo $my_background_variable; ?>;
  font-size: <?php echo $my_font_size; ?>;
}

Leave a Comment