Generating a static CSS file from dynamic options

Most themes these days include an options panel where you can change various aspects of your theme such as colors, font family, font size, et cetera.

There are many different ways of building an options panel to include with your theme, though my preferred method is via Advanced Custom Fields Pro.

Regardless of your method though, typically you retrieve settings from your options panel in PHP. For example, in Advanced Custom Fields you would get an option like this:

<?php $option_value = get_field('field_name', 'options'); ?>

To utilize this value in your CSS, you’d typically have to use inline CSS or pull in this CSS via a PHP file and then enqueue that PHP file in your site header.

This is not a particularly efficient method as it typically prevents site optimizers like WP-Rocket or W3 Total Cache from caching that CSS.

Generating a CSS file from a PHP file

Create a PHP file containing your dynamic CSS the way you typically would. For example:

$option_value = get_field('field_name', 'options');

echo '<style>

I typically call this file something like dynamic.css.php but you can call it whatever you want.

Adding the following code in your theme functions.php file will grab the CSS from this file and dump it into a new .css file:

add_action('parse_request', 'parse_dynamic_css_request');
function parse_dynamic_css_request($wp) {
	$ss_dir = get_stylesheet_directory(); // Shorten code, save 1 call
	ob_start(); // Capture all output (output buffering)
	require($ss_dir . '/css/dynamic.css.php'); // Generate CSS
	$css = ob_get_clean(); // Get generated CSS (output buffering)
	file_put_contents($ss_dir . '/css/static.css', $css, LOCK_EX); // Save it

I’d added commenting into the above function to explain what each part does.

It generates a file called “static.css” which you can then enqueue in your theme header:

wp_enqueue_style('your_dynamic_style', get_template_directory_uri().'/css/static.css');

By generating a static CSS file from your dynamic options, you can allow your users to be able to change various styling options on their website such as background colors, font colors, padding and margins, font sizes and more without taking a huge performance hit by having to inline all of this dynamically generated CSS.

This can be important when speed is an emphasis and you want to cache as much of your CSS as possible. Popular performance tests such as PageSpeed Insights often penalize websites with a lot of inline CSS, so this can also help boost your scores!

Questions or Comments?

Let me know below!

3 responses to “Generating a static CSS file from dynamic options”

  1. Ruth Rojas says:

    Thank you very much, this helps a lot.

  2. Christina says:

    Thank you so much for this! I was going crazy trying to figure this out. $5 tip dude!

Leave a Reply

Your email address will not be published. Required fields are marked *