wpseek.com
A WordPress-centric search engine for devs and theme authors



wp_get_typography_value_and_unit › WordPress Function

Since6.1.0
Deprecatedn/a
wp_get_typography_value_and_unit ( $raw_value, $options = array() )
Access:
  • private
Parameters: (2)
  • (string) $raw_value Raw size value from theme.json.
    Required: Yes
  • (array) $options { Optional. An associative array of options. Default is empty array. @type string $coerce_to Coerce the value to rem or px. Default `'rem'`. @type int $root_size_value Value of root font size for rem|em <-> px conversion. Default `16`. @type string[] $acceptable_units An array of font size units. Default `[ 'rem', 'px', 'em' ]`; }
    Required: No
    Default: array()
Returns:
  • (array|null) An array consisting of `'value'` and `'unit'` properties on success. `null` on failure.
Defined at:
Codex:

Checks a string for a unit and value and returns an array consisting of `'value'` and `'unit'`, e.g., [ '42', 'rem' ].



Source

function wp_get_typography_value_and_unit( $raw_value, $options = array() ) {
	if ( empty( $raw_value ) ) {
		return null;
	}

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

	$options = wp_parse_args( $options, $defaults );

	$acceptable_units_group = implode( '|', $options['acceptable_units'] );
	$pattern                = '/^(\d*\.?\d+)(' . $acceptable_units_group . '){1,1}$/';

	preg_match( $pattern, $raw_value, $matches );

	// Bails out if not a number value and a px or rem unit.
	if ( ! isset( $matches[1] ) || ! isset( $matches[2] ) ) {
		return null;
	}

	$value = $matches[1];
	$unit  = $matches[2];

	// 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'];
	}

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