Automattic\WooCommerce\Blocks
BlockTypesController::add_data_attributes()
Add data- attributes to blocks when rendered if the block is under the woocommerce/ namespace.
Method of the class: BlockTypesController{}
No Hooks.
Return
String
.
Usage
$BlockTypesController = new BlockTypesController(); $BlockTypesController->add_data_attributes( $content, $block );
- $content(string) (required)
- Block content.
- $block(array) (required)
- Parsed block data.
BlockTypesController::add_data_attributes() BlockTypesController::add data attributes code WC 9.4.2
public function add_data_attributes( $content, $block ) { $content = trim( $content ); if ( ! $this->block_should_have_data_attributes( $block['blockName'] ) ) { return $content; } $attributes = (array) $block['attrs']; $exclude_attributes = array( 'className', 'align' ); $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 ) ) { $value = $value ? 'true' : 'false'; } if ( ! is_scalar( $value ) ) { $value = wp_json_encode( $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 ); } // Set this last to prevent user-input from overriding it. $processor->set_attribute( 'data-block-name', $block['blockName'] ); return $processor->get_updated_html(); }