Dynamic styles allow you to control CSS output with PHP on-the-fly, based on your plugin’s options or simply instead of a preprocessor.
Note that wp_localize_script() is preferred in most cases, but you may still find this technique useful.
add_action('wp_enqueue_scripts', function() {
wp_enqueue_style('dynamic-style', plugins_url('style.php', __FILE__));
});
Learn how to use PHP Closures with WordPress Actions & Filters.
Put the code above in your plugin or theme’s functions.php
to enqueue the script. The key thing to note is that the filename of the style has a .php
extension.
header("Content-type: text/css; charset: UTF-8");
echo 'body { background: '.get_option('background-color', 'white').' }';
That would be your style.php
. Line 1 sends a header which makes browsers treat the file as a stylesheet and line 2 sets the value for the body background dynamically using WordPress’ options API.
A somewhat contrived example, but this could also be used to dynamically control a selector. Anything echo
‘d by style.php
will be served as CSS.
What about CSS Preprocessors?
The vast majority of applications for dynamic stylesheets with PHP can be done (and done better!) using CSS preprocessors such as SASS or LESS, which have the added advantage of making it easy to minify your styles on-the-fly.
I would only recommend the approach in this article for things like dynamic selectors or cases where a value needs to come from the database. Even then, I’d put the dynamic parts in a separate file so the majority of static styles can be minified, to minimise the amount of dynamic styles processed with each request.