Quick Tip: How to Auto Register all your Custom Blocks with WordPress 6.8

When developing either a multi-block plugin, or a theme that supports multiple custom blocks, you have to make sure all blocks get registered in PHP for them to become available within the editor.

In the past, this has either been a manual process with registrations for each block folder like so:

$block_types = array( 
  'accordion', 
  'carousel', 
  'carousel-slide', 
  'dialog', 
  'icon-button' 
);
foreach ( $block_types as $block_type ) {
    register_block_type( __DIR__ . "/build/{$block_type}" );
}

Or you could get fancy and write a custom function to scan your block directories and auto-register them.

<?php 
function fsdacf_register_all_blocks() {
	$block_directories = glob(PLUGIN_DIR . "/blocks/*", GLOB_ONLYDIR);

	foreach ($block_directories as $block) {
		register_block_type( $block );
	}
}
add_action( 'init', 'fsdacf_register_all_blocks' );

You can read more about how this works in my post on multi-block development workflows. The above operation is a bit expensive computationally though.

A better way at last!

Now in WordPress 6.8 there is a new function that helps streamline this process dramatically.

Introducing: wp_register_block_types_from_metadata_collection()

This function takes two arguments:

  1. The path to the folder all your individual blocks reside in
  2. The path to a block manifest file – which is essentially just like a large combination of all your block.json files, but as a PHP array instead of json.

From this, it will handle registering all your blocks for you.

wp_register_block_types_from_metadata_collection(
    __DIR__ . '/build',
    __DIR__ . '/build/blocks-manifest.php'
);

Your next logical question is probably how do I generate a file like this?

Luckily, there is a super easy flag in the @wordpress/scripts package to take care of this for you.

NOTE: you will need version ^30.14 of @wordpress/scripts or this will not work! So make sure you grab the latest version if you are working in an older repo.

We can modify our typical npm run build and npm run start commands to include an extra flag to generate this manifest for us:

  "scripts": {
    "start": "wp-scripts start --blocks-manifest --webpack-src-dir=blocks",
    "build": "wp-scripts build --blocks-manifest --webpack-src-dir=blocks"
  },

In this case, I have it pointing to a blocks folder specifically as the source, but this can be modified depending on your setup.

With this in place, you will never have to worry about forgetting to register a block after creating it again! As a bonus, it is much more performant than the directory globbing method mentioned above as well.