Cherry pick PR#50801 into trunk (#50813)

This commit is contained in:
Jorge A. Torres 2024-08-20 18:35:54 -03:00 committed by GitHub
parent 02596ba4b0
commit 7e6125ee76
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 25 additions and 11 deletions

View File

@ -227,20 +227,28 @@ final class BlockTypesController {
* @return string
*/
public function add_data_attributes( $content, $block ) {
$block_name = $block['blockName'];
if ( ! $this->block_should_have_data_attributes( $block_name ) ) {
$content = trim( $content );
if ( ! $this->block_should_have_data_attributes( $block['blockName'] ) ) {
return $content;
}
$attributes = (array) $block['attrs'];
$exclude_attributes = array( 'className', 'align' );
$escaped_data_attributes = array(
'data-block-name="' . esc_attr( $block['blockName'] ) . '"',
);
$attributes = (array) $block['attrs'];
$exclude_attributes = array( 'className', 'align' );
foreach ( $attributes as $key => $value ) {
if ( in_array( $key, $exclude_attributes, true ) ) {
$processor = new \WP_HTML_Tag_Processor( $content );
if (
false === $processor->next_token() ||
'DIV' !== $processor->get_token_name() ||
$processor->is_tag_closer()
) {
return $content;
}
foreach ( $attributes as $key => $value ) {
if ( ! is_string( $key ) || in_array( $key, $exclude_attributes, true ) ) {
continue;
}
if ( is_bool( $value ) ) {
@ -249,10 +257,16 @@ final class BlockTypesController {
if ( ! is_scalar( $value ) ) {
$value = wp_json_encode( $value );
}
$escaped_data_attributes[] = 'data-' . esc_attr( strtolower( preg_replace( '/(?<!\ )[A-Z]/', '-$0', $key ) ) ) . '="' . esc_attr( $value ) . '"';
// For output consistency, we convert camelCase to kebab-case and output in lowercase.
$key = strtolower( preg_replace( '/(?<!^|\ )[A-Z]/', '-$0', $key ) );
$processor->set_attribute( "data-{$key}", $value );
}
return preg_replace( '/^<div /', '<div ' . implode( ' ', $escaped_data_attributes ) . ' ', trim( $content ) );
// Set this last to prevent user-input from overriding it.
$processor->set_attribute( 'data-block-name', $block['blockName'] );
return $processor->get_updated_html();
}
/**