Automattic\WooCommerce\Blocks

BlockTypesController::add_data_attributes()publicWC 1.0

Add data- attributes to blocks when rendered if the block is under the woocommerce/ namespace.

Метод класса: BlockTypesController{}

Возвращает

Строку.

Использование

$BlockTypesController = new BlockTypesController();
$BlockTypesController->add_data_attributes( $content, $block );
$content(строка) (обязательный)
Block content.
$block(массив) (обязательный)
Parsed block data.

Код BlockTypesController::add_data_attributes() WC 8.7.0

public function add_data_attributes( $content, $block ) {
	$block_name      = $block['blockName'];
	$block_namespace = strtok( $block_name ?? '', '/' );

	/**
	 * Filters the list of allowed block namespaces.
	 *
	 * This hook defines which block namespaces should have block name and attribute `data-` attributes appended on render.
	 *
	 * @since 5.9.0
	 *
	 * @param array $allowed_namespaces List of namespaces.
	 */
	$allowed_namespaces = array_merge( array( 'woocommerce', 'woocommerce-checkout' ), (array) apply_filters( '__experimental_woocommerce_blocks_add_data_attributes_to_namespace', array() ) );

	/**
	 * Filters the list of allowed Block Names
	 *
	 * This hook defines which block names should have block name and attribute data- attributes appended on render.
	 *
	 * @since 5.9.0
	 *
	 * @param array $allowed_namespaces List of namespaces.
	 */
	$allowed_blocks = (array) apply_filters( '__experimental_woocommerce_blocks_add_data_attributes_to_block', array() );

	if ( ! in_array( $block_namespace, $allowed_namespaces, true ) && ! in_array( $block_name, $allowed_blocks, true ) ) {
		return $content;
	}

	$attributes              = (array) $block['attrs'];
	$exclude_attributes      = array( 'className', 'align' );
	$escaped_data_attributes = array(
		'data-block-name="' . esc_attr( $block['blockName'] ) . '"',
	);

	foreach ( $attributes as $key => $value ) {
		if ( in_array( $key, $exclude_attributes, true ) ) {
			continue;
		}
		if ( is_bool( $value ) ) {
			$value = $value ? 'true' : 'false';
		}
		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 ) . '"';
	}

	return preg_replace( '/^<div /', '<div ' . implode( ' ', $escaped_data_attributes ) . ' ', trim( $content ) );
}