Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 23 additions & 17 deletions inc/blocks.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
* Enqueue stylesheets for blocks. Each stylesheet will be enqueued on-render.
*
* @see https://developer.wordpress.org/reference/functions/wp_enqueue_block_style/
* @return void
*/
function enqueue_block_styles(): void {
$folder_path = get_entry_dir_path( 'block-styles', true );
Expand Down Expand Up @@ -50,35 +49,42 @@ function enqueue_block_styles(): void {
return;
}

$css_files = array_filter(
$block_directories = array_filter(
$folder_contents,
fn ( $item ): bool => pathinfo( (string) $item, PATHINFO_EXTENSION ) === 'css'
fn ( string $item ): bool => is_dir( $folder . '/' . $item ) && ! in_array( $item, [ '.', '..' ], true )
);

// Create entry details.
foreach ( $css_files as $css_file ) {
$block_name = preg_replace( '/\.css$/', '', $css_file );
$block_entries[] = [
'block_name' => $block_name,
'block_namespace' => $dir . '/' . $block_name,
'file_name' => $css_file,
'file_path' => $folder . '/',
'handle' => get_template() . '-' . $dir . '-' . $block_name,
];
// Create entry details for each block directory.
foreach ( $block_directories as $block_dir ) {
$block_folder = $folder . '/' . $block_dir;
$index_css_path = $block_folder . '/index.css';

// Check if index.css exists in the block directory.
if ( file_exists( $index_css_path ) ) {
$block_entries[] = [
'block_name' => $block_dir,
'block_namespace' => $dir . '/' . $block_dir,
'file_name' => 'index.css',
'file_path' => $block_folder,
'handle' => get_template() . '-' . $dir . '-' . $block_dir,
];
}
}
}

foreach ( $block_entries as $block ) {
$entry_dir = 'block-styles/' . $block['block_namespace'];

wp_enqueue_block_style(
$block['block_namespace'],
[
'handle' => $block['handle'] . '-styles', // Ex: `create-wordpress-theme-core-paragraph-styles`.
'src' => get_template_directory_uri() . '/build/block-styles/' . $block['block_namespace'] . '.css',
'deps' => get_asset_dependency_array( $block['block_namespace'] ),
'ver' => get_asset_version( $block['block_namespace'] ),
'src' => get_template_directory_uri() . '/build/' . trailingslashit( $entry_dir ) . $block['file_name'],
'deps' => get_asset_dependency_array( $entry_dir ),
'ver' => get_asset_version( $entry_dir ),

// Adding "path" allows inlining of block styles on the frontend when possible.
'path' => $block['file_path'] . $block['file_name'],
'path' => $block['file_path'] . '/' . $block['file_name'],
]
);
}
Expand Down
Loading