2 min read

Implementing Selectable Utility Classes (The Block Style Strategy)

A common request from clients is: "I want a dropdown list of classes like 'Box Shadow' or 'Hide on Mobile' in the Advanced tab, instead of typing them manually."

1. The Reality Check

Native WordPress limitation: You cannot populate the "Additional CSS Classes" input field in the Advanced tab with a dropdown list via theme.json. That field is strictly a text input for manual overrides.

The Solution: You register these classes as Block Styles in theme.json.

  • Behavior: They appear in the Styles (or Settings) sidebar as buttons or a dropdown.
  • Output: Selecting one adds a specific class (e.g., .is-style-card-shadow) to the block.

2. Example: Creating a "Card Shadow" Utility

Let's create a utility style for the Group block that adds a nice shadow and rounded corners.

Step A: Register in theme.json

Add this to styles.blocks.core/group.variations:

{
    "version": 3,
    "styles": {
        "blocks": {
            "core/group": {
                "variations": [
                    {
                        "name": "card-shadow",
                        "label": "Card Shadow",
                        "style": {
                            "border": {
                                "radius": "12px"
                            },
                            "shadow": "0px 10px 30px rgba(0,0,0,0.1)"
                        }
                    }
                ]
            }
        }
    }
}

Step B: The User Experience

  1. The user selects a Group block.
  2. They look at the Styles panel (half-moon icon or sidebar).
  3. They see a button labeled "Card Shadow".
  4. Clicking it applies the styles instantly.

3. Handling "CSS-Only" Utilities (e.g., Hide on Mobile)

Sometimes you can't define the style using theme.json properties (like display: none for mobile). In this case, you register the name in theme.json but write the CSS in your stylesheet.

1. Register the Label

{
    "name": "hide-mobile",
    "label": "Hide on Mobile",
    "style": {} // Leave empty! We just want the class name.
}

2. Write the CSS

In your theme's style.css:

@media (max-width: 767px) {
    .is-style-hide-mobile {
        display: none !important;
    }
}

4. The Limitation: No "Global" Utilities

Currently, theme.json requires you to register variations per block. You cannot register a "Shadow" style once and have it appear on Groups, Columns, and Images simultaneously.

Workaround: You must copy-paste the variation config into each block key (core/group, core/columns, core/image) in theme.json.

5. Summary

  • Do not try to hack the "Advanced" tab input without a plugin.
  • Do use Block Styles (variations) to create selectable UI options.
  • Do use the generated .is-style-{name} class for complex CSS in your stylesheet.