Skip to content

Instantly share code, notes, and snippets.

@wpmark
Last active October 31, 2024 08:57
Show Gist options
  • Save wpmark/d568910228e4b5775064ed42121d3260 to your computer and use it in GitHub Desktop.
Save wpmark/d568910228e4b5775064ed42121d3260 to your computer and use it in GitHub Desktop.
Easily enqueue a stylesheet for any block just by placing one in your theme.

Enqueue stylesheet for any WordPress block

Placing this function 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' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment