wp_img_tag_add_width_and_height_attr( string $image, string $context, int $attachment_id ): string

In this article

Adds width and height attributes to an img HTML tag.

Parameters

$imagestringrequired
The HTML img tag where the attribute should be added.
$contextstringrequired
Additional context to pass to the filters.
$attachment_idintrequired
Image attachment ID.

Return

string Converted 'img' element with 'width' and 'height' attributes added.

Source

 * Get loading optimization attributes to use.
 * This must occur before the conditional check below so that even images
 * that are ineligible for being lazy-loaded are considered.
 */
$optimization_attrs = wp_get_loading_optimization_attributes(
	'img',
	array(
		'src'           => $src,
		'width'         => $width,
		'height'        => $height,
		'loading'       => $loading_val,
		'fetchpriority' => $fetchpriority_val,
		'decoding'      => $decoding_val,
	),
	$context
);

// Images should have source for the loading optimization attributes to be added.
if ( ! str_contains( $image, ' src="' ) ) {
	return $image;
}

if ( empty( $decoding_val ) ) {
	/**
	 * Filters the `decoding` attribute value to add to an image. Default `async`.
	 *
	 * Returning a falsey value will omit the attribute.
	 *
	 * @since 6.1.0
	 *
	 * @param string|false|null $value      The `decoding` attribute value. Returning a falsey value
	 *                                      will result in the attribute being omitted for the image.
	 *                                      Otherwise, it may be: 'async', 'sync', or 'auto'. Defaults to false.
	 * @param string            $image      The HTML `img` tag to be filtered.
	 * @param string            $context    Additional context about how the function was called
	 *                                      or where the img tag is.
	 */
	$filtered_decoding_attr = apply_filters(
		'wp_img_tag_add_decoding_attr',
		isset( $optimization_attrs['decoding'] ) ? $optimization_attrs['decoding'] : false,
		$image,
		$context

Changelog

VersionDescription
5.5.0Introduced.

User Contributed Notes

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