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

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


Description Description

See also See also


Top ↑

Parameters Parameters

$attachment_id

(int) (Required) Image attachment ID.

$size

(array|string) (Optional) Image size. Accepts any valid image size, or an array of width and height values in pixels (in that order).

Default value: 'medium'

$image_meta

(array) (Optional) The image meta data as returned by 'wp_get_attachment_metadata()'.

Default value: null


Top ↑

Return Return

(string|bool) A 'srcset' value string or false.


Top ↑

Source Source

File: wp-includes/media.php

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

Top ↑

Changelog Changelog

Changelog
Version Description
4.4.0 Introduced.


Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note 1 content
    Contributed by Drew Jaynes

    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.