When working with the WordPress Theme Customizer, one of the things you may find yourself doing is writing out inline styles into one of the templates for your theme. Most likely, this will happen within the context of your header template since that’s where most of your styles and JavaScript sources are included.

Sure, it’s possible to handle a lot of the work via JavaScript and to use separate stylesheets to handle the general styles, but if you’re looking to set something up like, say, backgrounds that can be selected via the Theme Customizer, then you’re going to need to write out inline styles.

And if you’re in the habit of keeping your code separated such as styles reside in CSS files, behavior functionality resides in JavaScript files, and templates hold markup and PHP, then this can be a little bit annoying. It breaks the trend, you know?

There is somewhat of a solution to this, though.

Whenever I’ m working with the Theme Customizer, I make sure to do several things:

  1. Have a JavaScript file solely dedicated to working with the Theme Customizer API. I don’t want to mix that logic in with anything else as it’s got a single purpose that I don’t want cluttered with other code. I’ll combine it into a single script later, but during development, I will have a `theme-customizer.js`.
  2. Have a `theme-customizer.php` file that’s responsible or defining and setting up all of the functionality specficially for the theme and its relationship to the customizer. Here, all of the sections, settings, and other features are defined but nothing else. Like the JavaScript file, this file is used solely to integrate the customizer into the theme.

In addition to those two files, I also maintain a template part (or partial, as some refer to it), that I normally call customizer.php. The file may look something like this:

As you can tell from the code, the file is responsible for checking the values of the theme modifications via the WordPress API and then updating them accordingly via inline styles.

Though we can’t write this out directly into a separate CSS file (which would be ideal), we can write it out into a separate file that helps with maintainability throughout the course of a theme’s lifetime. Then, once it’s defined, you can easily include it in the header template with the following line (just after the wp_head):

It’s simple, sure, but things like this can go along way into making it much easier to keep your code logically separated into cohesive components that can be easily developed and maintained over time.