New WordPress features with block or hybrid themes are coming fast and furious these days, and it is difficult to find documentation on all the new features. I remember reading that only styles for the blocks used on the page would be added to pages. However, I noticed my custom hybrid theme was adding all block styles to all pages. (I am using blocks.json to register my custom blocks, and my hybrid theme sets up styles in theme.json – which is required for this to work.) A little googling, and I found a post on Make WordPress Core blog that explains how to fix this.
All it takes is one filter added to your custom block or hybrid theme’s functions.php to make block or hybrid themes only load styles (core block styles, and styles set up in theme.json or block.json) when needed:
add_filter( 'should_load_separate_core_block_assets', '__return_true' );
Easy answer if you know what to look for and where to look.
Details on what that filter does below (copied from the Make WordPress post):
wp-block-librarystylesheet changes: Instead of loading the
wp-includes/css/dist/block-library/style.cssfile which contains all styles for all blocks, this handle will now load the (much smaller)
wp-includes/css/dist/block-library/common.cssfile, which contains generic styles like the default colors definitions, basic styles for text alignments, and styles for the
- Styles for blocks will only get enqueued when the block gets rendered on a page.
Note: I am pretty sure this filter only automatically works for core blocks, and blocks that are registered with blocks.json. If your block stylesheets are added using
wp_enqueue_style, they will still be added to all pages.
Inline custom styles for core blocks
The Make WordPress post also has instructions on how to inline additional styles for core blocks only if the block is on the page. It is under the headline (no anchor, unfortunately): “Taking advantage of separate styles loading to add plugin/theme styles to blocks”.