WP_Theme_JSON::get_blocks_metadata() WordPress Method

The WP_Theme_JSON::get_blocks_metadata() method is used to get the metadata for all blocks in a theme. This is used to generate the theme.json file.

WP_Theme_JSON::get_blocks_metadata() #

Returns the metadata for each block.


Description

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': {}
  }
}

Top ↑

Return

(array) Block metadata.


Top ↑

Source

File: wp-includes/class-wp-theme-json.php

	protected static function get_blocks_metadata() {
		if ( null !== static::$blocks_metadata ) {
			return static::$blocks_metadata;
		}

		static::$blocks_metadata = array();

		$registry = WP_Block_Type_Registry::get_instance();
		$blocks   = $registry->get_all_registered();
		foreach ( $blocks as $block_name => $block_type ) {
			if (
				isset( $block_type->supports['__experimentalSelector'] ) &&
				is_string( $block_type->supports['__experimentalSelector'] )
			) {
				static::$blocks_metadata[ $block_name ]['selector'] = $block_type->supports['__experimentalSelector'];
			} else {
				static::$blocks_metadata[ $block_name ]['selector'] = '.wp-block-' . str_replace( '/', '-', str_replace( 'core/', '', $block_name ) );
			}

			if (
				isset( $block_type->supports['color']['__experimentalDuotone'] ) &&
				is_string( $block_type->supports['color']['__experimentalDuotone'] )
			) {
				static::$blocks_metadata[ $block_name ]['duotone'] = $block_type->supports['color']['__experimentalDuotone'];
			}

			// Assign defaults, then overwrite those that the block sets by itself.
			// If the block selector is compounded, will append the element to each
			// individual block selector.
			$block_selectors = explode( ',', static::$blocks_metadata[ $block_name ]['selector'] );
			foreach ( static::ELEMENTS as $el_name => $el_selector ) {
				$element_selector = array();
				foreach ( $block_selectors as $selector ) {
					$element_selector[] = $selector . ' ' . $el_selector;
				}
				static::$blocks_metadata[ $block_name ]['elements'][ $el_name ] = implode( ',', $element_selector );
			}
		}

		return static::$blocks_metadata;
	}


Top ↑

Changelog

Changelog
VersionDescription
5.9.0Added duotone key with CSS selector.
5.8.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.