Enqueue stylesheet for any WordPress block

Placing the function below into your theme or even in a plugin means that you can easily add a stylesheet for any WordPress block, core or otherwise.

Once the code is in place, you can simply add a stylesshet into the active theme in the /assets/blocks/ folder. The name of the file must block name with any forward slashes replaced with a hyphen.

For example, to ensure a custom stylesheet is loaded for the core heading block, create a stylsheet named core-heading.css and place it in the /assets/blocks/ folder in your theme. This stylesheet will then get enqueued.

<?php
/**
 * Enqueues a stylesheet for each block, if it exists in the theme.
 */
function hd_enqueue_block_styles() {

	// get all of the registered blocks.
	$blocks = WP_Block_Type_Registry::get_instance()->get_all_registered();

	// if we have block names.
	if ( ! empty( $blocks ) ) {

		// loop through each block name.
		foreach ( $blocks as $block ) {

			// replace slash with hyphen for filename.
			$slug = str_replace( '/', '-', $block->name );

			// get the file path for the block.
			$block_path = get_theme_file_path( "assets/blocks/{$slug}.css" );

			// if we have no file existing for this block.
			if ( ! file_exists( $block_path ) ) {
				continue;
			}

			// register a block stylesheet for this block.
			wp_register_style(
				'hd-block-' . $slug,
				get_theme_file_uri( "assets/blocks/{$slug}.css" ),
				[],
				filemtime( $block_path )
			);

			// enqueue a block stylesheet for buttons.
			wp_enqueue_block_style(
				$block->name,
				[
					'handle' => 'hd-block-' . $slug,
					'path'   => $block_path
				]
			);

		}

	}

}

add_action( 'init', 'hd_enqueue_block_styles' );