函数文档

wp_img_tag_add_width_and_height_attr()

💡 云策文档标注

概述

wp_img_tag_add_width_and_height_attr() 函数用于向 HTML img 标签添加 width 和 height 属性,以优化图像布局和性能。它通过解析图像源、应用过滤器并计算尺寸来实现此功能。

关键要点

  • 函数接受三个参数:$image(HTML img 标签字符串)、$context(上下文信息)和 $attachment_id(附件 ID),返回添加了 width 和 height 属性的 img 标签字符串。
  • 使用 wp_img_tag_add_width_and_height_attr 过滤器控制是否添加属性,默认值为 true,返回非 true 值将跳过添加。
  • 内部调用 wp_get_attachment_metadata() 获取图像元数据,wp_image_src_get_dimensions() 计算尺寸,并处理内联样式宽度以调整高度比例。
  • 主要用于 wp_filter_content_tags() 函数中,以自动处理文章内容中的图像标签。

代码示例

function wp_img_tag_add_width_and_height_attr( $image, $context, $attachment_id ) {
    $image_src = preg_match( '/src="([^"]+)"/', $image, $match_src ) ? $match_src[1] : '';
    list( $image_src ) = explode( '?', $image_src );
    if ( ! $image_src ) {
        return $image;
    }
    $add = apply_filters( 'wp_img_tag_add_width_and_height_attr', true, $image, $context, $attachment_id );
    if ( true === $add ) {
        $image_meta = wp_get_attachment_metadata( $attachment_id );
        $size_array = wp_image_src_get_dimensions( $image_src, $image_meta, $attachment_id );
        if ( $size_array && $size_array[0] && $size_array[1] ) {
            $style_width = preg_match( '/style="width:s*(d+)px;"/', $image, $match_width ) ? (int) $match_width[1] : 0;
            if ( $style_width ) {
                $size_array[1] = (int) round( $size_array[1] * $style_width / $size_array[0] );
                $size_array[0] = $style_width;
            }
            $hw = trim( image_hwstring( $size_array[0], $size_array[1] ) );
            return str_replace( '<img', '<img ' . $hw, $image );
        }
    }
    return $image;
}

注意事项

  • 函数在 WordPress 5.5.0 版本中引入,是核心功能的一部分,用于提升图像加载性能。
  • 如果无法解析图像源或过滤器返回非 true 值,函数将直接返回原始 img 标签而不添加属性。
  • 相关函数包括 wp_image_src_get_dimensions()、image_hwstring() 和 wp_get_attachment_metadata(),需确保这些函数正常工作以正确计算尺寸。

📄 原文内容

Adds width and height attributes to an img HTML tag.

Parameters

$imagestringrequired
The HTML img tag where the attribute should be added.
$contextstringrequired
Additional context to pass to the filters.
$attachment_idintrequired
Image attachment ID.

Return

string Converted 'img' element with 'width' and 'height' attributes added.

Source

function wp_img_tag_add_width_and_height_attr( $image, $context, $attachment_id ) {
	$image_src         = preg_match( '/src="([^"]+)"/', $image, $match_src ) ? $match_src[1] : '';
	list( $image_src ) = explode( '?', $image_src );

	// Return early if we couldn't get the image source.
	if ( ! $image_src ) {
		return $image;
	}

	/**
	 * Filters whether to add the missing `width` and `height` HTML attributes to the img tag. Default `true`.
	 *
	 * Returning anything else than `true` will not add the attributes.
	 *
	 * @since 5.5.0
	 *
	 * @param bool   $value         The filtered value, defaults to `true`.
	 * @param string $image         The HTML `img` tag where the attribute should be added.
	 * @param string $context       Additional context about how the function was called or where the img tag is.
	 * @param int    $attachment_id The image attachment ID.
	 */
	$add = apply_filters( 'wp_img_tag_add_width_and_height_attr', true, $image, $context, $attachment_id );

	if ( true === $add ) {
		$image_meta = wp_get_attachment_metadata( $attachment_id );
		$size_array = wp_image_src_get_dimensions( $image_src, $image_meta, $attachment_id );

		if ( $size_array && $size_array[0] && $size_array[1] ) {
			// If the width is enforced through style (e.g. in an inline image), calculate the dimension attributes.
			$style_width = preg_match( '/style="width:s*(d+)px;"/', $image, $match_width ) ? (int) $match_width[1] : 0;
			if ( $style_width ) {
				$size_array[1] = (int) round( $size_array[1] * $style_width / $size_array[0] );
				$size_array[0] = $style_width;
			}

			$hw = trim( image_hwstring( $size_array[0], $size_array[1] ) );
			return str_replace( '<img', "<img {$hw}", $image );
		}
	}

	return $image;
}

Hooks

apply_filters( ‘wp_img_tag_add_width_and_height_attr’, bool $value, string $image, string $context, int $attachment_id )

Filters whether to add the missing width and height HTML attributes to the img tag. Default true.

Changelog

Version Description
5.5.0 Introduced.