The register_block_script_handle() WordPress PHP function finds a script handle for the selected block metadata field. It automatically detects when a file path is provided and locates a corresponding asset file with details necessary to register the script under an autogenerated handle name. It returns an unprocessed script handle otherwise.
Usage
register_block_script_handle($metadata, $field_name, $index = 0);
Parameters
$metadata
(array) – Required. The block metadata.$field_name
(string) – Required. The field name to pick from metadata.$index
(int) – Optional. The index of the script to register when multiple items are passed. Default is 0.
More information
See WordPress Developer Resources: register_block_script_handle
Note: Registering a script via the block.json metadata file only works for plugins, not themes.
Examples
Register a script for a custom block
In this example, we’ll register a script for a custom block using block metadata.
Block metadata (block.json):
{ "apiVersion": 2, "name": "my-plugin/my-custom-block", "title": "My Custom Block", "category": "widgets", "editorScript": "file:./build/index.js" }
In your plugin PHP file:
function my_plugin_register_block() { $metadata = json_decode( file_get_contents( __DIR__ . '/block.json' ), true ); register_block_script_handle( $metadata, 'editorScript' ); } add_action( 'init', 'my_plugin_register_block' );
Register multiple scripts for a custom block
In this example, we’ll register multiple scripts for a custom block using block metadata.
Block metadata (block.json):
{ "apiVersion": 2, "name": "my-plugin/my-custom-block", "title": "My Custom Block", "category": "widgets", "editorScript": ["file:./build/index.js", "file:./build/another-script.js"] }
In your plugin PHP file:
function my_plugin_register_block() { $metadata = json_decode( file_get_contents( __DIR__ . '/block.json' ), true ); register_block_script_handle( $metadata, 'editorScript', 0 ); // Register the first script register_block_script_handle( $metadata, 'editorScript', 1 ); // Register the second script } add_action( 'init', 'my_plugin_register_block' );
Register scripts for multiple custom blocks
In this example, we’ll register scripts for multiple custom blocks using block metadata.
Block metadata (block-1.json):
{ "apiVersion": 2, "name": "my-plugin/my-first-block", "title": "My First Block", "category": "widgets", "editorScript": "file:./build/index-1.js" }
Block metadata (block-2.json):
{ "apiVersion": 2, "name": "my-plugin/my-second-block", "title": "My Second Block", "category": "widgets", "editorScript": "file:./build/index-2.js" }
In your plugin PHP file:
function my_plugin_register_blocks() { $metadata_1 = json_decode( file_get_contents( __DIR__ . '/block-1.json' ), true ); $metadata_2 =