Opened 15 months ago
Last modified 15 months ago
#61910 new defect (bug)
register_block_type_from_metadata fails to register style attribute when using $args
| Reported by: |
|
Owned by: | |
|---|---|---|---|
| Milestone: | Awaiting Review | Priority: | normal |
| Severity: | normal | Version: | |
| Component: | General | Keywords: | |
| Focuses: | Cc: |
Description
Summary
The register_block_type_from_metadata function fails to properly register a block's style attribute when the block is registered using the $args parameter instead of reading from a block.json file.
Steps to Reproduce
- Call
register_block_type_from_metadataand pass the block configuration in the$argsarray instead of reading fromblock.json. The first argument should be an empty string to specify ablock.jsonfile is not used. - Include a
styleattribute in$argsspecifying an array of style handles. - Observe a PHP warning about an undefined index 'name' when it attempts to call
register_block_style_handle.
Expected Result
The block should register successfully with the specified style attribute. No PHP warnings should be generated.
Actual Result
A PHP warning is emitted:
Warning: Undefined array key "name" in .../wp-includes/blocks.php on line 294
The style attribute is not properly registered for the block.
Relevant Code
The issue lies in this part of register_block_type_from_metadata:
foreach ( $style_fields as $metadata_field_name => $settings_field_name ) {
if ( ! empty( $settings[ $metadata_field_name ] ) ) {
$metadata[ $metadata_field_name ] = $settings[ $metadata_field_name ];
}
if ( ! empty( $metadata[ $metadata_field_name ] ) ) {
$styles = $metadata[ $metadata_field_name ];
$processed_styles = array();
if ( is_array( $styles ) ) {
for ( $index = 0; $index < count( $styles ); $index++ ) {
$result = register_block_style_handle(
$metadata,
$metadata_field_name,
$index
);
if ( $result ) {
$processed_styles[] = $result;
}
}
} else {
$result = register_block_style_handle(
$metadata,
$metadata_field_name
);
if ( $result ) {
$processed_styles[] = $result;
}
}
$settings[ $settings_field_name ] = $processed_styles;
}
}
When calling register_block_style_handle, it passes the $metadata array. However, when registering via $args, the block name is not present in $metadata. It only exists in $args/$settings at this point.
Unit Test
Here is a failing unit test that demonstrates the issue: (see attached)
The test currently fails due to the PHP warning.
Related
#56865, [57026] - Original change allowing register_block_type_from_metadata() to be used without a block.json file.
Failing Unit Test