Wordpress - How do I add CSS options to my plugin without using inline styles?
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; ?>;
}
Dynamically building a CSS file and then loading it adds a HUGE performance burden to what should be a very low bandwidth deal of adding a CSS file, especially if there are variables in the CSS that are going to be processed through WP. Because it is two different files being created for one page load, WP starts up twice and runs all the DB queries twice, and it's a big mess.
If your slider is only going to be on one page, and you want the styles set dynamically, then your best bet is to add a style block to the header.
In order of performance:
- Add small block of styles in header, dynamically created - Very fast
- Add a non-dynamic stylesheet via wp_enqueue_style - Medium
- Add a dynamic stylesheet via wp_enqueue_style - Very Slow
This is how I usually do it:
function build_stylesheet_url() {
echo '<link rel="stylesheet" href="' . $url . 'stylesheetname.css?build=' . date( "Ymd", strtotime( '-24 days' ) ) . '" type="text/css" media="screen" />';
}
function build_stylesheet_content() {
if( isset( $_GET['build'] ) && addslashes( $_GET['build'] ) == date( "Ymd", strtotime( '-24 days' ) ) ) {
header("Content-type: text/css");
echo "/* Something */";
define( 'DONOTCACHEPAGE', 1 ); // don't let wp-super-cache cache this page.
die();
}
}
add_action( 'init', 'build_stylesheet_content' );
add_action( 'wp_head', 'build_stylesheet_url' );