wp_get_attachment_image_srcset( int $attachment_id, string|int[] $size = 'medium', array|null $image_meta = null ): string|false

Retrieves the value for an image attachment’s ‘srcset’ attribute.

Description

See also

Parameters

$attachment_idintrequired
Image attachment ID.
$sizestring|int[]optional
Image size. Accepts any registered image size name, or an array of width and height values in pixels (in that order). Default 'medium'.

Default:'medium'

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

Default:null

Return

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

Source

 *
 * @since 4.4.0
 *
 * @see wp_calculate_image_srcset()
 *
 * @param int          $attachment_id Image attachment ID.
 * @param string|int[] $size          Optional. Image size. Accepts any registered image size name, or an array of
 *                                    width and height values in pixels (in that order). Default 'medium'.
 * @param array|null   $image_meta    Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
 *                                    Default null.
 * @return string|false A 'srcset' value string or false.
 */
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;
	}

Changelog

VersionDescription
4.4.0Introduced.

User Contributed Notes

  1. Skip to note 2 content

    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( get_custom_header()->attachment_id, array( 400, 200 ) );
    ?>
    <img src="<?php header_image(); ?>" srcset="<?php echo esc_attr( $srcset ); ?>">

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