WP_Theme_JSON::convert_variables_to_value()
Replaces CSS variables with their values in place.
Method of the class: WP_Theme_JSON{}
No Hooks.
Return
Array
.
Usage
$result = WP_Theme_JSON::convert_variables_to_value( $styles, $values );
- $styles(array) (required)
- CSS declarations to convert.
- $values(array) (required)
- key => value pairs to use for replacement.
Changelog
Since 6.3.0 | Introduced. |
Since 6.5.0 | Check for empty style before processing its value. |
WP_Theme_JSON::convert_variables_to_value() WP Theme JSON::convert variables to value code WP 6.6.2
private static function convert_variables_to_value( $styles, $values ) { foreach ( $styles as $key => $style ) { if ( empty( $style ) ) { continue; } if ( is_array( $style ) ) { $styles[ $key ] = self::convert_variables_to_value( $style, $values ); continue; } if ( 0 <= strpos( $style, 'var(' ) ) { // find all the variables in the string in the form of var(--variable-name, fallback), with fallback in the second capture group. $has_matches = preg_match_all( '/var\(([^),]+)?,?\s?(\S+)?\)/', $style, $var_parts ); if ( $has_matches ) { $resolved_style = $styles[ $key ]; foreach ( $var_parts[1] as $index => $var_part ) { $key_in_values = 'var(' . $var_part . ')'; $rule_to_replace = $var_parts[0][ $index ]; // the css rule to replace e.g. var(--wp--preset--color--vivid-green-cyan). $fallback = $var_parts[2][ $index ]; // the fallback value. $resolved_style = str_replace( array( $rule_to_replace, $fallback, ), array( isset( $values[ $key_in_values ] ) ? $values[ $key_in_values ] : $rule_to_replace, isset( $values[ $fallback ] ) ? $values[ $fallback ] : $fallback, ), $resolved_style ); } $styles[ $key ] = $resolved_style; } } } return $styles; }