wp_get_typography_value_and_unit()WP 6.1.0

Checks a string for a unit and value and returns an array consisting of 'value' and 'unit', e.g. array( '42', 'rem' ).

No Hooks.

Returns

array|null. An array consisting of 'value' and 'unit' properties on success. null on failure.

Usage

wp_get_typography_value_and_unit( $raw_value, $options ): ?array;
$raw_value(string|int|float) (required)
Raw size value from theme.json.
$options(array)

An associative array of options.

Default: empty array

  • coerce_to(string)
    Coerce the value to rem or px.
    Default: 'rem'

  • root_size_value(int)
    Value of root font size for rem|em <-> px conversion.
    Default: 16

  • acceptable_units(string[])
    An array of font size units. Default array( 'rem', 'px', 'em' );

Changelog

Since 6.1.0 Introduced.

wp_get_typography_value_and_unit() code WP 7.1

function wp_get_typography_value_and_unit( $raw_value, $options = array() ): ?array {
	if ( ! is_string( $raw_value ) && ! is_int( $raw_value ) && ! is_float( $raw_value ) ) {
		_doing_it_wrong(
			__FUNCTION__,
			__( 'Raw size value must be a string, integer, or float.' ),
			'6.1.0'
		);
		return null;
	}

	if ( empty( $raw_value ) ) {
		return null;
	}

	// Converts numbers to pixel values by default.
	if ( is_numeric( $raw_value ) ) {
		$raw_value = $raw_value . 'px';
	}

	$defaults = array(
		'coerce_to'        => '',
		'root_size_value'  => 16,
		'acceptable_units' => array( 'rem', 'px', 'em' ),
	);

	/**
	 * @var array{
	 *     coerce_to: string,
	 *     root_size_value: positive-int,
	 *     acceptable_units: non-empty-array<non-empty-string>,
	 * } $options
	 */
	$options = wp_parse_args( $options, $defaults );

	// Bails out if the raw value can't be parsed.
	if ( ! preg_match( '/^(\d*\.?\d+)([a-zA-Z]+|%)$/', $raw_value, $matches ) ) {
		return null;
	}

	$value = (float) $matches[1];
	$unit  = $matches[2];

	if ( ! in_array( $unit, $options['acceptable_units'], true ) ) {
		return null;
	}

	/*
	 * Default browser font size. Later, possibly could inject some JS to
	 * compute this `getComputedStyle( document.querySelector( "html" ) ).fontSize`.
	 */
	if ( 'px' === $options['coerce_to'] && ( 'em' === $unit || 'rem' === $unit ) ) {
		$value = $value * $options['root_size_value'];
		$unit  = $options['coerce_to'];
	}

	if ( 'px' === $unit && ( 'em' === $options['coerce_to'] || 'rem' === $options['coerce_to'] ) ) {
		$value = $value / $options['root_size_value'];
		$unit  = $options['coerce_to'];
	}

	/*
	 * No calculation is required if swapping between em and rem yet,
	 * since we assume a root size value. Later we might like to differentiate between
	 * :root font size (rem) and parent element font size (em) relativity.
	 */
	if ( ( 'em' === $options['coerce_to'] || 'rem' === $options['coerce_to'] ) && ( 'em' === $unit || 'rem' === $unit ) ) {
		$unit = $options['coerce_to'];
	}

	return array(
		'value' => round( $value, 3 ),
		'unit'  => $unit,
	);
}