函数文档

wp_image_add_srcset_and_sizes()

💡 云策文档标注

概述

wp_image_add_srcset_and_sizes() 是一个 WordPress 函数,用于向现有的 HTML 'img' 元素添加 'srcset' 和 'sizes' 属性,以支持响应式图像。它基于图像元数据和附件 ID 计算并插入这些属性。

关键要点

  • 函数接受三个参数:$image(HTML 'img' 元素字符串)、$image_meta(图像元数据数组)和 $attachment_id(附件 ID),返回添加了 'srcset' 和 'sizes' 属性的 'img' 元素字符串。
  • 内部逻辑包括验证图像元数据、提取图像源、检查编辑状态、获取图像尺寸,并调用 wp_calculate_image_srcset() 和 wp_calculate_image_sizes() 辅助函数进行计算。
  • 函数在 WordPress 4.4.0 版本中引入,主要用于 wp_img_tag_add_srcset_and_sizes_attr() 函数中,以自动为图像添加响应式属性。

代码示例

function wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id ) {
    // 确保图像元数据存在。
    if ( empty( $image_meta['sizes'] ) ) {
        return $image;
    }

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

    // 如果无法获取图像源,则提前返回。
    if ( ! $image_src ) {
        return $image;
    }

    // 如果图像已插入并后来编辑过,则提前退出。
    if ( preg_match( '/-e[0-9]{13}/', $image_meta['file'], $img_edit_hash )
        && ! str_contains( wp_basename( $image_src ), $img_edit_hash[0] )
    ) {
        return $image;
    }

    $width  = preg_match( '/ width="([0-9]+)"/', $image, $match_width ) ? (int) $match_width[1] : 0;
    $height = preg_match( '/ height="([0-9]+)"/', $image, $match_height ) ? (int) $match_height[1] : 0;

    if ( $width && $height ) {
        $size_array = array( $width, $height );
    } else {
        $size_array = wp_image_src_get_dimensions( $image_src, $image_meta, $attachment_id );
        if ( ! $size_array ) {
            return $image;
        }
    }

    $srcset = wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id );

    if ( $srcset ) {
        // 检查是否已有 'sizes' 属性。
        $sizes = strpos( $image, ' sizes=' );

        if ( ! $sizes ) {
            $sizes = wp_calculate_image_sizes( $size_array, $image_src, $image_meta, $attachment_id );
        }
    }

    if ( $srcset && $sizes ) {
        // 格式化 'srcset' 和 'sizes' 字符串并转义属性。
        $attr = sprintf( ' srcset="%s"', esc_attr( $srcset ) );

        if ( is_string( $sizes ) ) {
            $attr .= sprintf( ' sizes="%s"', esc_attr( $sizes ) );
        }

        // 将 srcset 和 sizes 属性添加到图像标记中。
        return preg_replace( '/]+?)[/ ]*>/', '', $image );
    }

    return $image;
}

注意事项

  • 函数依赖于 wp_calculate_image_srcset() 和 wp_calculate_image_sizes() 来计算属性值,确保这些辅助函数正常工作。
  • 如果图像元数据中缺少 'sizes' 键或图像源无法提取,函数会提前返回原始 'img' 元素,避免错误。
  • 在编辑图像后,函数会检查编辑哈希以匹配图像文件,防止为旧版本图像添加属性。

📄 原文内容

Adds ‘srcset’ and ‘sizes’ attributes to an existing ‘img’ element.

Description

See also

Parameters

$imagestringrequired
An HTML 'img' element to be filtered.
$image_metaarrayrequired
The image meta data as returned by ‘wp_get_attachment_metadata() ‘.
$attachment_idintrequired
Image attachment ID.

Return

string Converted 'img' element with 'srcset' and 'sizes' attributes added.

Source

function wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id ) {
	// Ensure the image meta exists.
	if ( empty( $image_meta['sizes'] ) ) {
		return $image;
	}

	$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;
	}

	// Bail early if an image has been inserted and later edited.
	if ( preg_match( '/-e[0-9]{13}/', $image_meta['file'], $img_edit_hash )
		&& ! str_contains( wp_basename( $image_src ), $img_edit_hash[0] )
	) {
		return $image;
	}

	$width  = preg_match( '/ width="([0-9]+)"/', $image, $match_width ) ? (int) $match_width[1] : 0;
	$height = preg_match( '/ height="([0-9]+)"/', $image, $match_height ) ? (int) $match_height[1] : 0;

	if ( $width && $height ) {
		$size_array = array( $width, $height );
	} else {
		$size_array = wp_image_src_get_dimensions( $image_src, $image_meta, $attachment_id );
		if ( ! $size_array ) {
			return $image;
		}
	}

	$srcset = wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id );

	if ( $srcset ) {
		// Check if there is already a 'sizes' attribute.
		$sizes = strpos( $image, ' sizes=' );

		if ( ! $sizes ) {
			$sizes = wp_calculate_image_sizes( $size_array, $image_src, $image_meta, $attachment_id );
		}
	}

	if ( $srcset && $sizes ) {
		// Format the 'srcset' and 'sizes' string and escape attributes.
		$attr = sprintf( ' srcset="%s"', esc_attr( $srcset ) );

		if ( is_string( $sizes ) ) {
			$attr .= sprintf( ' sizes="%s"', esc_attr( $sizes ) );
		}

		// Add the srcset and sizes attributes to the image markup.
		return preg_replace( '/<img ([^>]+?)[/ ]*>/', '<img $1' . $attr . ' />', $image );
	}

	return $image;
}

Changelog

Version Description
4.4.0 Introduced.