Loading ACF Custom Blocks Style In <head>

Recently I started working with ACF Custom Blocks and the latest way of registering custom blocks using block.json. It is working great and so easy to start creating blocks.

While everything was going smoothly, I noticed that the CSS file I added in “style” in block.json is loaded in the footer and on every page even if the block is not added on that page.
I started “googling” and found out that I can load the style only on the pages where the block is added by using

add_filter( 'should_load_separate_core_block_assets', '__return_true' );

This worked great, but then I noticed the style is loaded in the footer and that is not something I like, so googled more, but found nothing.

I decided to check how everything works in the WordPress Core in terms of rendering the block and loading the files and I came up with the following solution which seems to be working fine.

This is the block.json file:

{
    "name": "acf/example-block",
    "title": "Example ACF Block",
    "description": "Simple ACF block.",
    "category": "text",
    "icon": "align-left",
    "acf": {
        "renderTemplate": "template.php"
    },
    "supports": {
        "align": false,
        "anchor": false,
        "color": {
            "text": true,
            "background": true
        }
    },
    "style": ["file:./style-index.css"],
    "script": ["file:./index.js"]
}

This is the code:

add_filter( 'block_type_metadata_settings', function( $settings, $metadata ) {
   if ( is_admin() ) {
	return $settings;
   }

   add_action( 'wp_enqueue_scripts', function() use ( $settings ) {
	global $post;

	if ( has_block( $settings['name'], $post->ID ) ) {
		foreach ( $settings['style_handles'] as $style_handle ) {
		      wp_enqueue_style( $style_handle );
		}
	}
   });

   $settings['style_handles'] = array();

   return $settings;
}, 10, 2 );

You Might Be Interested In