wp_img_tag_add_srcset_and_sizes_attr() WordPress Function

The wp_img_tag_add_srcset_and_sizes_attr() function allows you to automatically add srcset and sizes attributes to image tags within your Wordpress content. This can be useful for responsive design, or simply to reduce the file size of images being served to your users.

wp_img_tag_add_srcset_and_sizes_attr( string $image, string $context, int $attachment_id ) #

Adds srcset and sizes attributes to an existing img HTML tag.


Parameters

$image

(string)(Required)The HTML img tag where the attribute should be added.

$context

(string)(Required)Additional context to pass to the filters.

$attachment_id

(int)(Required)Image attachment ID.


Top ↑

Return

(string) Converted 'img' element with 'loading' attribute added.


Top ↑

Source

File: wp-includes/media.php

function wp_img_tag_add_srcset_and_sizes_attr( $image, $context, $attachment_id ) {
	/**
	 * Filters whether to add the `srcset` and `sizes` HTML attributes to the img tag. Default `true`.
	 *
	 * Returning anything else than `true` will not add the attributes.
	 *
	 * @since 5.5.0
	 *
	 * @param bool   $value         The filtered value, defaults to `true`.
	 * @param string $image         The HTML `img` tag where the attribute should be added.
	 * @param string $context       Additional context about how the function was called or where the img tag is.
	 * @param int    $attachment_id The image attachment ID.
	 */
	$add = apply_filters( 'wp_img_tag_add_srcset_and_sizes_attr', true, $image, $context, $attachment_id );

	if ( true === $add ) {
		$image_meta = wp_get_attachment_metadata( $attachment_id );
		return wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id );
	}

	return $image;
}


Top ↑

Changelog

Changelog
VersionDescription
5.5.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More
Show More