coding
Dynamically generate static CSS files using PHP
If you are a premium theme developer, there may be times when you will need to generate dynamic CSS/JavaScript files to be used inside your theme. An example to this is when you want the users to be able to change certain aspects of the CSS including colors, backgrounds, padding, borders, or add their own CSS classes/id’s.
Introduction
There are a few popular approaches that theme developers used, including directly inserting the CSS code inside header.php, or call it from a style.php file.
But these approaches have problems of its own. For example, inserting CSS directly skips the wp_enqueue_style and still adding a few PHP calls to the header every time the page loads; or using style.php would not only adding more PHP calls, but also require the server to load WordPress twice which is a no-no. Worse of all, none of these methods provide an ideal environment for cache plugins like W3 Total Cache. Ultimately, nothing beats the old school way which is a static CSS (e.g. styles.css) which is then enqueued inside functions.php – and that’s the direction I’m going with this tutorial.
The method
1. Create a styles.php file containing your CSS codes. Below is just an example.
/*---------------------- Body --------------------------*/
body {
background:<?php echo $data['body_background_color']; ?>;
color:<?php echo $data['body_font']['color']; ?>;
font-family: <?php echo $data['body_font']['face']; ?>;
font-size: <?php echo $data['body_font']['size']; ?>;
}Notice that we have none of the bloated header("Content-type: text/css"); or include '../../../../wp-load.php';. Also, since I’m using the SMOF, my serialized options data can be called using $data['id']. Yours might look a little different, for example get_option('my_body_color').
2. Create a function to generate the static CSS file using styles.php
We are going to create a function that generates a static CSS file, then place this file inside our theme folder. This function is written inside admin-functions.php of the SMOF.
function generate_options_css($newdata) {
$data = $newdata;
$css_dir = get_stylesheet_directory() . '/css/'; // Shorten code, save 1 call
ob_start(); // Capture all output (output buffering)
require($css_dir . 'styles.php'); // Generate CSS
$css = ob_get_clean(); // Get generated CSS (output buffering)
file_put_contents($css_dir . 'options.css', $css, LOCK_EX); // Save it
}Since that’s more than a few lines I’m going to explain them by bits.
- $newdata is the input which the function will process. Here I am converting the variable to $data so that I can use it inside
styles.php. More on that later. - $css_dir defines the folder of which your CSS file will be stored.
- ob_start() , ob_get_clean() – these are the two magic functions that will capture whatever was called inside styles.php, and store them inside $css.
- Finally, your newly generated css codes will be printed on a file called
options.cssusingfile_put_contents()
3. Using the function
This is the most important part. The rule of thumb is, the CSS file MUST ONLY be generated when the variables inside styles.php were changed. Otherwise, this defeats the purpose of taking the trouble of generating a static CSS file to minimize the number of PHP calls on page load. For this tutorial, I’m just going to explain how it is done inside SMOF. It should serve as a guide for usage in other areas e.g. plugins or shortcodes – I’d probably write another tutorial for that in the future.
I’m going to hook the function every time the user saves or resets the options, using this line of code:
generate_options_css($data); //generate static CSS file
This went into two areas inside admin-interface.php of the SMOF. The first area is when the ajax save action is called somewhere on line 710, after update_option(OPTIONS, $data);. The final code would look like this:
update_option(OPTIONS, $data); generate_options_css($data); //generate static CSS file
The second area is when the user resets the options, somewhere on line 35-37, after update_option(OPTIONS,$defaults);. The final code would look something like this:
$defaults = (array) $options_machine->Defaults; update_option(OPTIONS,$defaults); generate_options_css($defaults); //generate static css file
4. Register your static CSS file and enqueue it to your header.
From this point forward, everything else is pretty much straight forward. Here’s a little snippet of my functions.php file.
function themename_enqueue_css() {
wp_register_style('options', get_template_directory_uri() . '/css/options.css', 'style');
wp_enqueue_style( 'options');
}
add_action('wp_print_styles', 'themename_enqueue_css');
DONE!
As a wrap up, this is the summary of this tutorial:
- Create a function to generate a static CSS file
- Call this function only when the options were changed
- Register and enqueue your static CSS file in your themes’
functions.phpfile.
And why this is better:
- Minimize the number of PHP calls every time the page loads
- Avoid using wp-load that loads WordPress twice.
- Cleaner and standard-driven coding.
I hope you find this article useful and help you to spawn more creative ways to implement it inside your themes, plugins, shortcodes, and widgets. Note that this same trick can be used for other types of files including, yes, JavaScript!. ![]()











Shawn
16/10/2021 at 17:33
I’m not seeing any of this code in the smof files that you mention. Do you have a modified vs. of smof that incorporates these changes?
*btw, loving smof. Having been a woothemes user for years now it is nice to see a setup that I can use in my own themes and the dynamically generated static css file is a huge addition.
thank you
CodeRevolution
16/10/2021 at 17:35
Thank you for comment Shawn. Just sharing what I said to you earlier on Twitter in case someone else is wondering the same thing:
The reason that I didn’t port this modification on SMOF before is because of the lack of documentation – which would only confuse the people who wants to use SMOF in their themes. Therefore I decided to write this article in advance before this mod is added into the next release.
Hope that helps 🙂
Shawn
16/10/2021 at 17:37
Looking forward to the updated vs. as I tried what you posted here but it didn’t seem to work. I’m probably missing something stupid, so better to wait than to go crazy trying.
One thing that is making it more difficult for me is that I am using this in a plugin vs. a theme so the paths are totally different.
It’s a weird scenario where I am creating a bbpress ‘theme plugin’. Basically a theme that is in a plugin –long story but is the right way of doing this particular project according to the dev JJ.
This means I am trying to generate a css file in a weird location.
plugin structure:
/my-plugin/
–/admin/ — smof
–/theme-name/css/ – where I am trying to save the css file created
–functions.php – includes calls to admin, smof works great with tweaks
also:
I noticed that smof is quite different than the original vs. Are you planning on adding his sanitization functions later?
should have mentioned the bug I ran into:
When I add generate_options_css($data); //generate static css file in the 2 spots you mention and reload the plugin it shows up fine. However if I click save, nothing happens, spinner just spins. No errors or anything just spinning
CodeRevolution
16/10/2021 at 17:38
Shawn, I took a look at your codes and I saw a few errors. Here’s your codes updated https://dl.dropbox.com/u/45581457/my-plugin.zip
1 – You need to use generate_options_css($defaults); and not generate_options_css($data); for the reset.
2. Use paths to your plugin and not URL. Try WP_PLUGIN_DIR or plugin_dir_path($file) instead of WP_PLUGIN_URL
3. styles.php should not have undefined id’s, otherwise that will spit out errors in wp_debug
Additionally, I also fixed the header location after reset to “optionsframework” (line 39 admin-interface.php)
To avoid future problems, I would also suggest you to change this header location to something else e.g. myplugin, since it may conflict with themes that also uses optionsframework in their themes.
Hope that helps 🙂
Shawn
16/10/2021 at 17:39
Wow, thank you so much for taking the time to help me out with this. I did download the new zip but noticed the file that has all the paths and initializes the plugin isn’t in the zip. There are the two folders admin/ my-custom-theme/.
Can you send me the modified plugin file with the changes you are talking about?
*I spent a lot of time reading through your plugin and it’s really really nice. Having used woo for so long it was cool to see how you kept the same structure but added some cool functionality at the same time
CodeRevolution
16/10/2021 at 17:40
My bad. I was forking it inside TwentyEleven theme, completely forgotten that it was supposed to be a plugin!
Here’s the updated code complete with correct file paths and some examples inside styles.php http://dl.dropbox.com/u/45581457/1-my-plugin.zip
Also just as a reminder since you’re using SMOF as a plugin, I would strongly suggest you to change filepaths definitions e.g. ADMIN_PATH etc and also change the prefixes like of_ , of- , optionsframework etc. You know the drill 🙂
Shawn
16/10/2021 at 17:40
thank you.
I’ll make all the changes from the new files and see if I can get it working. Basically the biggest problem I am fighting is with my file paths, as I call the function to enqueue the css in a custom place, and a few other issues.
I’ve been working my way through it this morning, and will check the new files to see what i have been doing wrong.
I seriously appreciate this help!
Shawn
16/10/2021 at 17:41
Got it all sorted out, just a couple of tweaks and it is working perfectly now!
As to changing the paths:
Is it simply a matter of doing a find and replace for the following in all files?
of_
of-
optionsframework
Are those 3 the only ones required to change?
thinking of doing a simple find and replace across the entire admin directory.
CodeRevolution
16/10/2021 at 17:42
As far as I can remember, yup. Don’t forget the css and js files too. 🙂