Generate CSS Variables for any global style assigned in the site editor

One trick to maintainable CSS is the use of CSS Variables. For example, I might be building custom blocks that include some form elements, like a submit button. I’d love for my submit button to use the same default font-family that the other buttons on the site use, but how do I get that information out of theme.json or out of the site editor?

I need to reference a CSS property that was assigned to a specific block or element, but WordPress doesn’t always print the value as a CSS variable for extenders to use.

The solution is to pull the value out of the global styles using either wp_get_global_styles() or wp_get_global_settings(). With these two functions you have access to every design setting you see in theme.json – even if the value has been overridden in the site editor. These are the same functions WordPress core uses to determine all of the CSS rules. (And yes it’d be nice if it just printed everything as CSS variables automatically.)

By checking the global styles array, we can find the fontFamily that the user has picked out for buttons ($styles['elements']['button']['typography']['fontFamily']), and then output that value as our own custom CSS variable.

Then in my custom block, I can assign the font-family for my submit button to that custom CSS variable.

The full code is below but there’s a few things to remember:

  1. When using CSS variables that you don’t control, always include a fallback value.
  2. We need to load our styles for the frontend and for the block editor to be able to see them.
  3. Loading for the frontend can be done with the wp_print_styles hook.
  4. To load custom inline styles for the block editor, it’s a little trickier. You need to already be enqueueing a stylesheet for your plugin, theme, or block, and then use wp_add_inline_style() to tack on your additional custom CSS.
  5. You can definitely extend this to go beyond buttons!

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.