How to add dynamic CSS to WordPress with wp_add_inline_style()

Screen Shot 2016-06-16 at 7.42.45 AM

As you start to develop sites, you’ll find yourself wanting to add CSS to your sites that is based on some sort of dynamic value, which could include user input, such at theme color pickers, or post/term meta, for example to brand each category with a particular colour.

You could create a PHP-driven CSS file, but this is quite heavy and slow for your site. Since WordPress 3.3, there’s been a better way to add this to your site, though it isn’t talked about much.

wp_add_inline_style() allows you to add extra CSS rules directly inline after an enqueued CSS file has been loaded. This means that after your enqueued CSS file is called, inline CSS using the HTML <style> tags will be added immediately afterwards. This provides several benefits including being able to override styles in your enqueued stylesheet if you have any custom values set.

Implementation

The usage of wp_add_inline_style() is really quite simple. All you need to provide is the handle of the stylesheet you want to add the CSS to and then the CSS declarations themselves.

Recall that when you register or enqueue a CSS file, you need to provide a “handle”, or reference name. In the enqueue example below, parent-theme is the handle.

So if you wanted to add some dynamic styles to that CSS file, wp_add_inline_style() will add them inline after the CSS is loaded. To do so, you could do something like this:

This code grabs two pieces of term meta from each term in a given taxonomy: a section color specified by a color picker to “brand” the magazine section, and any custom styles that can be added as needed for a specific term.

When data is set for this term meta and the CSS is appended to the stylesheet, your page source will look something like this:

You can see then how you can override styles in any given stylesheet as these CSS rules are added after the stylesheet they’re appended to is enqueued, allowing you to provide default styles in a stylesheet and dynamically override them based on whatever data you like. That could be term meta for branding each term, user meta for the status of whether or not they have completed a set of forms or post meta for the time of day the post was published. The sky’s the limit.

Leave a Reply