How to work with custom styles saved in theme option?

I am creating a theme where user can save custom styles from theme customizer through settings API. Those style info are saved in options table as serialized data.

When Custom skin is active I will have to print those css styles in the site. There are three route I might go about it.

  1. Printing custom styles on header area with <style> tag.
  2. Creating a custom.css.php file where I print those styles.
  3. Create a css file using php file operation and save those styles whenever user saves custom styles.

All those have pros and cons

  1. Printing inside <head> using <style>: The theme will be used by internet marketers and they are concerned about code to text ratio. Adding a 20-30 lines of css code will increase code ratio.
  2. Creating CSS file using PHP header(): WordPress functions isn’t available. Will need to load them which is inefficient. Also IE have some issues with this method.

  3. Writing a CSS file whenever user saves custom style: It seems to be a good idea. But I don’t have enough knowledge about what is the pros and cons of this method. And if there is any permission issues the theme may be facing when it installed in various servers by users. I will appreciate if you could enlighten me on this topic.

So, What is the right way to go with in this situation.

1
1

When your users really need 30 lines of custom CSS, your theme is flawed. Create a set of predefined styles instead (dark and light scheme, sans and serif fonts etc.) and prepare your main stylesheet for these cases. You can hook into body_class then and add the classes you need to get these styles.
Adjustments for your users should be very minimal then.

Using an endpoint for a PHP generated stylesheet is something like your second option. That’s not a problem in IE, and a caching plugin will help reducing the processing time further. I would use the timestamp of the last change for the endpoint, eg.:

example.com/css/012345678/

… to make sure the browser fetches the freshest stylesheet and caches the file as it should.

Option 3 means: you have to save the file per Filesystem API, you have to make sure it isn’t deleted later (tricky!), and you should replace the old file to avoid insane amounts of CSS files. Forcing the new file to replace the cached file without an additional GET parameter isn’t easy too.

Use an endpoint.

Leave a Comment