wp_get_attachment_image_sizes()WP 4.4.0

Retrieves the value for an image attachment's 'sizes' attribute.

1 time — 0.000911 sec (slow) | 50000 times — 30 sec (slow)

No Hooks.

Return

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

Usage

wp_get_attachment_image_sizes( $attachment_id, $size, $image_meta );
$attachment_id(int) (required)
Image attachment ID.
$size(string|int[])
Image size. Accepts any registered image size name, or an array of width and height values in pixels (in that order).
Default: 'medium'
$image_meta(array)
The image meta data as returned by wp_get_attachment_metadata().
Default: null

Examples

0

#1 Just get the dimensions of the attachment image for the attribute

echo wp_get_attachment_image_sizes( 10, 'full' );
// output:
// (max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 984px) 61vw, (max-width: 1362px) 45vw, 600px
0

#2 Use in the IMG tag

<img
	src="<?php echo wp_get_attachment_image_url( $attachment_id, 'full' ) ?>"
	srcset="<?php echo wp_get_attachment_image_srcset( $attachment_id, 'full' ) ?>"
	sizes="<?php echo wp_get_attachment_image_sizes( $attachment_id, 'full' ) ?>"
>

We get it:

<img
	src="http://example.com/wp-content/uploads/2015/12/image.png"
	srcset="http://example.com/wp-content/uploads/2015/12/image-240x300.png 240w, http://example.com/wp-content/uploads/2015/12/image.png 700w"
	sizes="(max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 984px) 61vw, (max-width: 1362px) 45vw, 600px"
>

Notes

Changelog

Since 4.4.0 Introduced.

wp_get_attachment_image_sizes() code WP 6.4.3

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