generate_block_asset_handle( string $block_name, string $field_name, int $index ): string

In this article

Generates the name for an asset based on the name of the block and the field name provided.

Parameters

$block_namestringrequired
Name of the block.
$field_namestringrequired
Name of the metadata field.
$indexintoptional
Index of the asset when multiple items passed.
Default 0.

Return

string Generated asset name for the block’s field.

Source

function generate_block_asset_handle( $block_name, $field_name, $index = 0 ) {
	if ( str_starts_with( $block_name, 'core/' ) ) {
		$asset_handle = str_replace( 'core/', 'wp-block-', $block_name );
		if ( str_starts_with( $field_name, 'editor' ) ) {
			$asset_handle .= '-editor';
		}
		if ( str_starts_with( $field_name, 'view' ) ) {
			$asset_handle .= '-view';
		}
		if ( str_ends_with( strtolower( $field_name ), 'scriptmodule' ) ) {
			$asset_handle .= '-script-module';
		}
		if ( $index > 0 ) {
			$asset_handle .= '-' . ( $index + 1 );
		}
		return $asset_handle;
	}

	$field_mappings = array(
		'editorScript'     => 'editor-script',
		'editorStyle'      => 'editor-style',
		'script'           => 'script',
		'style'            => 'style',
		'viewScript'       => 'view-script',
		'viewScriptModule' => 'view-script-module',
		'viewStyle'        => 'view-style',
	);
	$asset_handle   = str_replace( '/', '-', $block_name ) .
		'-' . $field_mappings[ $field_name ];
	if ( $index > 0 ) {
		$asset_handle .= '-' . ( $index + 1 );
	}
	return $asset_handle;
}

Changelog

VersionDescription
6.5.0Added support for viewScriptModule field.
6.1.0Added $index parameter.
5.5.0Introduced.

User Contributed Notes

You must log in before being able to contribute a note or feedback.