In WordPress 5.5, conditional loading of core block styles was introduced to only load the style of a block if it’s actually used on the current page. This works fine, but what if you change a core block to make use of another block, which is not necessarily available on the page yet? This would result in an unstyled block.

In my case, I adjusted the latest posts block to actually display a proper button block for the “read more” link (more on how I exactly achieved that will come in the next blog post). But since the button block is not rendered as block, the styling is missing.

My solution was to enqueue the button block style during the render block function of the latest posts block, which looks like this using the filter render_block_{$this->name}:

 * Enqueue the button block style for latest posts.
 * @param   string  $block_content Block content
 * @return  string Updated block content
function my_add_button_block_style_to_latest_posts( string $block_content ): string {
    \wp_enqueue_style( 'wp-block-button' );

    return $block_content;

\add_filter( 'render_block_core/latest-posts', 'my_add_button_block_style_to_latest_posts' );
Code language: PHP (php)

Now, whenever the latest posts block is being rendered, the button block styles are enqueued as well so that my custom block is displayed properly.

Leave a Reply

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