WP_Theme_JSON::flatten_tree() WordPress Method

The WP_Theme_JSON::flatten_tree() method is used to flatten an array of theme objects into a single array. This is useful for creating a list of all available themes, or for creating a list of themes that are compatible with a specific plugin or theme.

WP_Theme_JSON::flatten_tree( array $tree, string $prefix = '', string $token = '--' ) #

Given a tree, it creates a flattened one by merging the keys and binding the leaf values to the new keys.


Description

It also transforms camelCase names into kebab-case and substitutes ‘/’ by ‘-‘.

This is thought to be useful to generate CSS Custom Properties from a tree, although there’s nothing in the implementation of this function that requires that format.

For example, assuming the given prefix is ‘–wp’ and the token is ‘–‘, for this input tree:

{
  'some/property': 'value',
  'nestedProperty': {
    'sub-property': 'value'
  }
}

it’ll return this output:

{
  '--wp--some-property': 'value',
  '--wp--nested-property--sub-property': 'value'
}

Top ↑

Parameters

$tree

(array)(Required)Input tree to process.

$prefix

(string)(Optional) Prefix to prepend to each variable.

Default value: ''

$token

(string)(Optional) Token to use between levels.

Default value: '--'


Top ↑

Return

(array) The flattened tree.


Top ↑

Source

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

	protected static function flatten_tree( $tree, $prefix = '', $token = '--' ) {
		$result = array();
		foreach ( $tree as $property => $value ) {
			$new_key = $prefix . str_replace(
				'/',
				'-',
				strtolower( _wp_to_kebab_case( $property ) )
			);

			if ( is_array( $value ) ) {
				$new_prefix = $new_key . $token;
				$result     = array_merge(
					$result,
					static::flatten_tree( $value, $new_prefix, $token )
				);
			} else {
				$result[ $new_key ] = $value;
			}
		}
		return $result;
	}


Top ↑

Changelog

Changelog
VersionDescription
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.