Automattic\WooCommerce\EmailEditor\Integrations\Core\Renderer\Blocks

Post_Template::normalize_image_for_email │ private │ WC 1.0

Sanitize a raw <img> and normalize it for a grid cell.

Reuses Html_Processing_Helper::sanitize_image_html() for the security pass (attribute allowlist, URL/style sanitizing), then pins the display width to the cell and replaces the web-only styling with the responsive email style. WordPress stores the intrinsic file width (e.g. width="1024") which Outlook honors literally, and the core web style carries a width: 100% that collapses once the image is out of a CSS grid — so both are overwritten with a concrete cell width plus {@see self::IMAGE_STYLE}.

Method of the class: Post_Template{}

No Hooks.

Returns

string. Normalized <img> HTML, or an empty string when the image has no usable src.

Usage

// private - for code of main (parent) class only
$result = $this->normalize_image_for_email( $img_html, $cell_width ): string;
$img_html(string) (required)
Raw <img> HTML.
$cell_width(int) (required)
Cell content width in px.

Post_Template::normalize_image_for_email() code WC 11.1.2

private function normalize_image_for_email( string $img_html, int $cell_width ): string {
	if ( '' === $img_html ) {
		return '';
	}

	$sanitized = Html_Processing_Helper::sanitize_image_html( $img_html );

	$html = new \WP_HTML_Tag_Processor( $sanitized );
	if ( ! $html->next_tag( array( 'tag_name' => 'img' ) ) ) {
		return '';
	}

	$src = $html->get_attribute( 'src' );
	if ( ! is_string( $src ) || '' === $src ) {
		return '';
	}

	// Scale the stored height to the cell width so the image keeps its aspect ratio in clients
	// that read the attributes (Outlook). A missing/oversized/non-numeric dimension just leaves
	// the height to `height: auto` in the style.
	$raw_width  = $html->get_attribute( 'width' );
	$raw_height = $html->get_attribute( 'height' );
	$width      = is_string( $raw_width ) && is_numeric( $raw_width ) ? (int) $raw_width : 0;
	$height     = is_string( $raw_height ) && is_numeric( $raw_height ) ? (int) $raw_height : 0;
	if ( $width > 0 && $height > 0 ) {
		$scaled_height = max( 1, (int) round( $height * ( $cell_width / $width ) ) );
		$html->set_attribute( 'height', esc_attr( (string) $scaled_height ) );
	} else {
		$html->remove_attribute( 'height' );
	}

	$html->set_attribute( 'width', esc_attr( (string) $cell_width ) );

	// Drop the web-only class (harmless in email, and the core/image renderer strips it too) and
	// replace the web styling with the responsive email style.
	$html->remove_attribute( 'class' );
	$html->set_attribute( 'style', esc_attr( self::IMAGE_STYLE ) );

	return $html->get_updated_html();
}