How to filter styles for WordPress blocks with layout supportUpdated
I spent much of June working on a forward-looking WordPress theme, in anticipation of “Full Site Editing” arriving in WordPress 5.9 at the end of 2021.1 There was a small snag early on with the CSS syntax delivered inline alongside the new layout-supported Group block: it presumes one type of layout model by default.
What follows is a solution for customising the contents of a Group block’s
style element, to match the requirements of a different layout model.
Default styles for blocks with layout support
First, what does “layout support” mean? The settings panel for a Group block in WordPress 5.8+ offers a configurable Layout option, allowing user-defined widths to be set from inside the block editor.
For dynamic width values to work they must be scoped to each block. WordPress handles this by inlining a style element, with styles scoped to a unique auto-generated class per block. Unfortunately, these styles presume a layout model using
max-width paired with
margin-left: auto; margin-right: auto. Child elements are also presumed to use CSS floats for horizontal alignment.
How to manage this style element for a layout model requiring different CSS syntax?
Filtering the layout style element
The layout support styles are printed by a function found at wp-includes/block-supports/layout.php:
wp_render_layout_support_flag(). Touching this directly is not an option, but the good news here is there’s a filter that makes it easy to take over and print a tailored
style element via a custom function.
Adding custom CSS
Working with a copy of the original function, the key part is assigning new CSS declarations to the
style variable. This snippet 2 demonstrates how I’m returning styles for a layout model based on CSS Grid syntax, with the resulting
style element returned like this:
Unhooking native functions
To prevent multiple style elements being loaded per block, it’s necessary to run
remove_filter for the native core function. The Gutenberg plugin currently (as of v10.9.1) has its own implementation which should also be unhooked.