diff --git a/plugins/woocommerce/src/Blocks/BlockTypesController.php b/plugins/woocommerce/src/Blocks/BlockTypesController.php index ac2f5240c14..5eb5ab2c8a0 100644 --- a/plugins/woocommerce/src/Blocks/BlockTypesController.php +++ b/plugins/woocommerce/src/Blocks/BlockTypesController.php @@ -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( '/(?set_attribute( "data-{$key}", $value ); } - return preg_replace( '/^
set_attribute( 'data-block-name', $block['blockName'] ); + return $processor->get_updated_html(); } /**