WP_Theme_JSON::get_blocks_metadata()protected staticWP 5.8.0

Returns the metadata for each block.

Example:

{
  'core/paragraph': {
	'selector': 'p',
	'elements': {
	  'link' => 'link selector',
	  'etc'  => 'element selector'
	}
  },
  'core/heading': {
	'selector': 'h1',
	'elements': {}
  },
  'core/image': {
	'selector': '.wp-block-image',
	'duotone': 'img',
	'elements': {}
  }
}

Method of the class: WP_Theme_JSON{}

No Hooks.

Return

Array. Block metadata.

Usage

$result = WP_Theme_JSON::get_blocks_metadata();

Changelog

Since 5.8.0 Introduced.
Since 5.9.0 Added duotone key with CSS selector.
Since 6.1.0 Added features key with block support feature level selectors.
Since 6.3.0 Refactored and stabilized selectors API.

WP_Theme_JSON::get_blocks_metadata() code WP 6.5.2

protected static function get_blocks_metadata() {
	$registry = WP_Block_Type_Registry::get_instance();
	$blocks   = $registry->get_all_registered();

	// Is there metadata for all currently registered blocks?
	$blocks = array_diff_key( $blocks, static::$blocks_metadata );
	if ( empty( $blocks ) ) {
		return static::$blocks_metadata;
	}

	foreach ( $blocks as $block_name => $block_type ) {
		$root_selector = wp_get_block_css_selector( $block_type );

		static::$blocks_metadata[ $block_name ]['selector']  = $root_selector;
		static::$blocks_metadata[ $block_name ]['selectors'] = static::get_block_selectors( $block_type, $root_selector );

		$elements = static::get_block_element_selectors( $root_selector );
		if ( ! empty( $elements ) ) {
			static::$blocks_metadata[ $block_name ]['elements'] = $elements;
		}

		// The block may or may not have a duotone selector.
		$duotone_selector = wp_get_block_css_selector( $block_type, 'filter.duotone' );

		// Keep backwards compatibility for support.color.__experimentalDuotone.
		if ( null === $duotone_selector ) {
			$duotone_support = isset( $block_type->supports['color']['__experimentalDuotone'] )
				? $block_type->supports['color']['__experimentalDuotone']
				: null;

			if ( $duotone_support ) {
				$root_selector    = wp_get_block_css_selector( $block_type );
				$duotone_selector = static::scope_selector( $root_selector, $duotone_support );
			}
		}

		if ( null !== $duotone_selector ) {
			static::$blocks_metadata[ $block_name ]['duotone'] = $duotone_selector;
		}

		// If the block has style variations, append their selectors to the block metadata.
		if ( ! empty( $block_type->styles ) ) {
			$style_selectors = array();
			foreach ( $block_type->styles as $style ) {
				$style_selectors[ $style['name'] ] = static::get_block_style_variation_selector( $style['name'], static::$blocks_metadata[ $block_name ]['selector'] );
			}
			static::$blocks_metadata[ $block_name ]['styleVariations'] = $style_selectors;
		}
	}

	return static::$blocks_metadata;
}