Automattic\WooCommerce\EmailEditor\Integrations\Utils

Styles_Helper::convert_to_pxpublic staticWC 1.0

Convert a CSS value to a static px value for email clients.

This is mostly for use in font size, spacing, etc.

Method of the class: Styles_Helper{}

No Hooks.

Returns

?String. The static pixel value (e.g., 30px).

Usage

$result = Styles_Helper::convert_to_px( $input, $use_fallback, ?int $base_font_size ): ?string;
$input(string) (required)
The CSS value to convert.
$use_fallback(true|false)
Whether to use the fallback value if the input is not a valid CSS value.
Default: true
?int $base_font_size
.
Default: 16

Styles_Helper::convert_to_px() code WC 10.4.3

public static function convert_to_px( string $input, bool $use_fallback = true, ?int $base_font_size = 16 ): ?string {
	$fallback = $use_fallback ? $base_font_size . 'px' : null;

	if ( ! $input ) {
		return $fallback;
	}

	$input = trim( $input );

	// Validate input against potentially malicious values.
	if ( preg_match( '/[<>"\']/', $input ) ) {
		return $fallback;
	}

	if ( str_ends_with( $input, 'px' ) ) {
		// If already in px, return as is.
		return $input;
	}
	if ( str_ends_with( $input, 'rem' ) || str_ends_with( $input, 'em' ) ) {
		// Convert rem/em to px (assuming 16px base).
		$value = (float) str_replace( array( 'rem', 'em' ), '', $input );
		return round( $value * $base_font_size ) . 'px';
	}
	if ( str_ends_with( $input, '%' ) ) {
		// Convert percentage to px (assuming 16px base).
		$value = (float) str_replace( '%', '', $input );
		return round( ( $value / 100 ) * $base_font_size ) . 'px';
	}
	if ( is_numeric( $input ) ) {
		// If it's just a number, assume px.
		return $input . 'px';
	}

	return $fallback;
}