wp_get_attachment_image_srcset()WP 4.4.0

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

1 time — 0.001658 sec (very slow) | 50000 times — 35.26 sec (very slow)

No Hooks.

Return

String|false. A 'srcset' value string or false.

Usage

wp_get_attachment_image_srcset( $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|null)
The image meta data as returned by wp_get_attachment_metadata().
Default: null

Examples

0

#1 Get the srcset value for the full size image

echo wp_get_attachment_image_srcset( 6587, 'full' );
// output:
// http://example.com/wp-content/uploads/2015/12/WP-Recall-0-120x69.jpg 120w, http://example.com/wp-content/uploads/2015/12/WP-Recall-0.jpg 975w
0

#2 Add the srcset attribute to the image

$attachment_id = 6587;

printf( '<img src="%s" srcset="%s">',
	wp_get_attachment_image_url( $attachment_id ),
	wp_get_attachment_image_srcset( $attachment_id, 'full' )
);

/* output:
<img
	src="/wp-content/uploads/2015/12/WP-Recall-0-80x80.jpg"
	srcset="http://wp-kama.ru/wp-content/uploads/2015/12/WP-Recall-0-120x69.jpg 120w, 
			http://wp-kama.ru/wp-content/uploads/2015/12/WP-Recall-0.jpg 975w"
>
*/
0

#3 Adding the necessary attributes to the IMG

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

#4 Using $size as an array of width and height dimensions:

<?php
// Specifying width of 400 (px) and height of 200 (px).
$srcset = wp_get_attachment_image_srcset( $attachment_id, [ 400, 200 ] );
?>

<img src="<?php header_image(); ?>" srcset="<?php echo esc_attr( $srcset ); ?>">

Notes

Changelog

Since 4.4.0 Introduced.

wp_get_attachment_image_srcset() code WP 6.5.4

function wp_get_attachment_image_srcset( $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_srcset( $size_array, $image_src, $image_meta, $attachment_id );
}