wp_img_tag_add_width_and_height_attr

函数
wp_img_tag_add_width_and_height_attr ( $image, $context, $attachment_id )
参数
  • (string) $image The HTML `img` tag where the attribute should be added.
    Required:
  • (string) $context Additional context to pass to the filters.
    Required:
  • (int) $attachment_id Image attachment ID.
    Required:
返回值
  • (string) Converted 'img' element with 'width' and 'height' attributes added.
定义位置
相关方法
wp_img_tag_add_loading_attrwp_img_tag_add_decoding_attrwp_img_tag_add_srcset_and_sizes_attrwp_iframe_tag_add_loading_attrwp_image_add_srcset_and_sizes
引入
5.5.0
弃用
-

wp_img_tag_add_width_and_height_attr是一个为HTML img标签添加宽度和高度属性的函数。这些属性指定了图片的尺寸,这可以帮助浏览器更快地渲染页面,防止页面加载时出现布局偏移。

为`img’HTML标签添加`width’和`height’属性。

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 ) {
			$hw = trim( image_hwstring( $size_array[0], $size_array[1] ) );
			return str_replace( '<img', "<img {$hw}", $image );
		}
	}

	return $image;
}

常见问题

FAQs
查看更多 >