WP_Theme_JSON::get_css_variablesprotectedWP 5.8.0

Converts each styles section into a list of rulesets to be appended to the stylesheet. These rulesets contain all the css variables (custom variables and preset variables).

See glossary at https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax

For each section this creates a new ruleset such as:

block-selector {
  --wp--preset--category--slug: value;
  --wp--custom--variable: value;
}

Method of the class: WP_Theme_JSON{}

No Hooks.

Returns

String. The new stylesheet.

Usage

// protected - for code of main (parent) or child class
$result = $this->get_css_variables( $nodes, $origins );
$nodes(array) (required)
Nodes with settings.
$origins(string[]) (required)
List of origins to process.

Changelog

Since 5.8.0 Introduced.
Since 5.9.0 Added the $origins parameter.

WP_Theme_JSON::get_css_variables() code WP 7.1

protected function get_css_variables( $nodes, $origins ) {
	$stylesheet = '';
	foreach ( $nodes as $metadata ) {
		if ( null === $metadata['selector'] ) {
			continue;
		}

		$selector          = $metadata['selector'];
		$feature_selectors = $metadata['selectors'] ?? array();
		$node              = _wp_array_get( $this->theme_json, $metadata['path'], array() );

		/*
		 * Group preset declarations by selector. Blocks that define
		 * feature-level selectors need their preset CSS variables
		 * output under that feature selector instead of the block's
		 * root selector.
		 */
		$vars_by_selector              = array();
		$vars_by_selector[ $selector ] = array();

		foreach ( static::PRESETS_METADATA as $preset_metadata ) {
			if ( empty( $preset_metadata['css_vars'] ) ) {
				continue;
			}

			$values_by_slug = static::get_settings_values_by_slug( $node, $preset_metadata, $origins );
			if ( empty( $values_by_slug ) ) {
				continue;
			}

			$target = static::get_feature_selector( $feature_selectors, $preset_metadata['path'][0], $selector );

			if ( ! isset( $vars_by_selector[ $target ] ) ) {
				$vars_by_selector[ $target ] = array();
			}

			foreach ( $values_by_slug as $slug => $value ) {
				$vars_by_selector[ $target ][] = array(
					'name'  => static::replace_slug_in_string( $preset_metadata['css_vars'], $slug ),
					'value' => $value,
				);
			}
		}

		// Theme vars always use the block's default selector.
		foreach ( static::compute_theme_vars( $node ) as $theme_var ) {
			$vars_by_selector[ $selector ][] = $theme_var;
		}

		foreach ( $vars_by_selector as $rule_selector => $declarations ) {
			$stylesheet .= static::to_ruleset( $rule_selector, $declarations );
		}
	}

	return $stylesheet;
}