WP_Theme_JSON::flatten_tree()
Given a tree, it creates a flattened one by merging the keys and binding the leaf values to the new keys.
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' }
Method of the class: WP_Theme_JSON{}
No Hooks.
Return
Array
. The flattened tree.
Usage
$result = WP_Theme_JSON::flatten_tree( $tree, $prefix, $token );
- $tree(array) (required)
- Input tree to process.
- $prefix(string)
- Prefix to prepend to each variable.
Default: empty string - $token(string)
- Token to use between levels.
Default: '--'
Changelog
Since 5.8.0 | Introduced. |
WP_Theme_JSON::flatten_tree() WP Theme JSON::flatten tree code WP 6.8
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; $flattened_subtree = static::flatten_tree( $value, $new_prefix, $token ); foreach ( $flattened_subtree as $subtree_key => $subtree_value ) { $result[ $subtree_key ] = $subtree_value; } } else { $result[ $new_key ] = $value; } } return $result; }