wp_calculate_image_sizes( string|int[] $size, string|null $image_src = null, array|null $image_meta = null, int $attachment_id ): string|false

In this article

Creates a ‘sizes’ attribute value for an image.

Parameters

$sizestring|int[]required
Image size. Accepts any registered image size name, or an array of width and height values in pixels (in that order).
$image_srcstring|nulloptional
The URL to the image file.

Default:null

$image_metaarray|nulloptional
The image meta data as returned by ‘wp_get_attachment_metadata() ‘.

Default:null

$attachment_idintoptional
Image attachment ID. Either $image_meta or $attachment_id is needed when using the image size name as argument for $size. Default 0.

Return

string|false A valid source size value for use in a 'sizes' attribute or false.

Source

function wp_get_attachment_image_sizes( $attachment_id, $size = 'medium', $image_meta = null ) {
	$image = wp_get_attachment_image_src( $attachment_id, $size );

	if ( ! $image ) {
		return false;
	}

	if ( ! is_array( $image_meta ) ) {
		$image_meta = wp_get_attachment_metadata( $attachment_id );
	}

	$image_src  = $image[0];
	$size_array = array(
		absint( $image[1] ),
		absint( $image[2] ),
	);

	return wp_calculate_image_sizes( $size_array, $image_src, $image_meta, $attachment_id );
}

/**
 * Creates a 'sizes' attribute value for an image.
 *
 * @since 4.4.0
 *
 * @param string|int[] $size          Image size. Accepts any registered image size name, or an array of
 *                                    width and height values in pixels (in that order).
 * @param string|null  $image_src     Optional. The URL to the image file. Default null.
 * @param array|null   $image_meta    Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
 *                                    Default null.
 * @param int          $attachment_id Optional. Image attachment ID. Either `$image_meta` or `$attachment_id`
 *                                    is needed when using the image size name as argument for `$size`. Default 0.
 * @return string|false A valid source size value for use in a 'sizes' attribute or false.
 */
function wp_calculate_image_sizes( $size, $image_src = null, $image_meta = null, $attachment_id = 0 ) {
	$width = 0;

	if ( is_array( $size ) ) {
		$width = absint( $size[0] );

Changelog

VersionDescription
4.4.0Introduced.

User Contributed Notes

You must log in before being able to contribute a note or feedback.