Automattic\WooCommerce\EmailEditor\Integrations\Utils
Html_Processing_Helper::sanitize_image_html
Sanitize image HTML while preserving necessary attributes for email rendering.
Метод класса: Html_Processing_Helper{}
Хуков нет.
Возвращает
Строку. Sanitized image HTML.
Использование
$result = Html_Processing_Helper::sanitize_image_html( $image_html ): string;
- $image_html(строка) (обязательный)
- Raw image HTML.
Код Html_Processing_Helper::sanitize_image_html() Html Processing Helper::sanitize image html WC 10.4.3
public static function sanitize_image_html( string $image_html ): string {
// If no HTML tags, return as-is.
if ( false === strpos( $image_html, '<' ) ) {
return $image_html;
}
// Extract img tag using regex for reliable processing.
if ( ! preg_match( '/<img[^>]*>/i', $image_html, $matches ) ) {
return $image_html;
}
$img_tag = $matches[0];
$sanitized_attributes = array();
$has_src = false;
// Extract and sanitize individual attributes using WP_HTML_Tag_Processor for attribute processing.
$html = new \WP_HTML_Tag_Processor( $img_tag );
if ( $html->next_tag() ) {
$attributes = $html->get_attribute_names_with_prefix( '' );
if ( is_array( $attributes ) ) {
foreach ( $attributes as $attr_name ) {
$attr_value = $html->get_attribute( $attr_name );
// Sanitize specific attributes.
switch ( $attr_name ) {
case 'src':
// Sanitize image source URL.
$sanitized_src = esc_url( (string) $attr_value );
if ( ! empty( $sanitized_src ) ) {
$sanitized_attributes[] = $attr_name . '="' . $sanitized_src . '"';
$has_src = true;
}
break;
case 'alt':
case 'width':
case 'height':
// Sanitize text attributes.
$sanitized_attributes[] = $attr_name . '="' . esc_attr( (string) $attr_value ) . '"';
break;
case 'class':
// Clean CSS classes.
$cleaned_classes = self::clean_css_classes( (string) $attr_value );
if ( ! empty( $cleaned_classes ) ) {
$sanitized_attributes[] = $attr_name . '="' . esc_attr( $cleaned_classes ) . '"';
}
break;
case 'style':
// Sanitize inline styles - only allow safe properties for email rendering.
$sanitized_styles = self::sanitize_image_styles( (string) $attr_value );
if ( ! empty( $sanitized_styles ) ) {
$sanitized_attributes[] = $attr_name . '="' . esc_attr( $sanitized_styles ) . '"';
}
break;
}
}
}
}
// If no valid src attribute, return empty string.
if ( ! $has_src ) {
return '';
}
// Rebuild the img tag with sanitized attributes.
if ( empty( $sanitized_attributes ) ) {
return '';
}
return '<img ' . implode( ' ', $sanitized_attributes ) . '>';
}