The generate_block_asset_handle() WordPress PHP function generates the name for an asset based on the name of the block and the field name provided.
Usage
$asset_name = generate_block_asset_handle('my_block', 'my_field', 1);
In this example, the function takes in the block name ‘my_block’, the field name ‘my_field’, and an optional index ‘1’. It will return the generated asset name.
Parameters
- $block_name (string) – Required. Name of the block.
- $field_name (string) – Required. Name of the metadata field.
- $index (int) – Optional. Index of the asset when multiple items passed. Default is 0.
More Information
See WordPress Developer Resources: generate_block_asset_handle()
Examples
Generating a Basic Asset Handle
This example generates a basic asset handle using the block name and field name. The default index (0) is used.
$block_name = 'header'; $field_name = 'background'; $asset_handle = generate_block_asset_handle($block_name, $field_name); // Output: "header-background-0"
Generating an Asset Handle with Custom Index
This example generates an asset handle with a custom index.
$block_name = 'footer'; $field_name = 'color'; $index = 2; $asset_handle = generate_block_asset_handle($block_name, $field_name, $index); // Output: "footer-color-2"
Generating Multiple Asset Handles
This example generates multiple asset handles for the same block and field, but with different indices.
$block_name = 'sidebar'; $field_name = 'layout'; for ($i = 0; $i < 3; $i++) { $asset_handle = generate_block_asset_handle($block_name, $field_name, $i); echo $asset_handle . "\n"; } // Output: // "sidebar-layout-0" // "sidebar-layout-1" // "sidebar-layout-2"
Generating Asset Handles for Different Blocks
This example generates asset handles for different blocks using the same field name and index.
$blocks = ['header', 'footer', 'sidebar']; $field_name = 'color'; $index = 1; foreach ($blocks as $block_name) { $asset_handle = generate_block_asset_handle($block_name, $field_name, $index); echo $asset_handle . "\n"; } // Output: // "header-color-1" // "footer-color-1" // "sidebar-color-1"
Generating Asset Handles for Different Fields
This example generates asset handles for different fields within the same block and index.
$block_name = 'header'; $fields = ['background', 'color', 'font']; $index = 0; foreach ($fields as $field_name) { $asset_handle = generate_block_asset_handle($block_name, $field_name, $index); echo $asset_handle . "\n"; } // Output: // "header-background-0" // "header-color-0" // "header-font-0"