Adds width
and height
attributes to an img
HTML tag.
Parameters
$image
stringrequired- The HTML
img
tag where the attribute should be added. $context
stringrequired- Additional context to pass to the filters.
$attachment_id
intrequired- Image attachment ID.
Source
}
return $image;
}
/**
* Adds `width` and `height` attributes to an `img` HTML tag.
*
* @since 5.5.0
*
* @param string $image The HTML `img` tag where the attribute should be added.
* @param string $context Additional context to pass to the filters.
* @param int $attachment_id Image attachment ID.
* @return string Converted 'img' element with 'width' and 'height' attributes added.
*/
function wp_img_tag_add_width_and_height_attr( $image, $context, $attachment_id ) {
$image_src = preg_match( '/src="([^"]+)"/', $image, $match_src ) ? $match_src[1] : '';
list( $image_src ) = explode( '?', $image_src );
// Return early if we couldn't get the image source.
if ( ! $image_src ) {
return $image;
}
/**
* Filters whether to add the missing `width` and `height` 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_width_and_height_attr', true, $image, $context, $attachment_id );
if ( true === $add ) {
$image_meta = wp_get_attachment_metadata( $attachment_id );
$size_array = wp_image_src_get_dimensions( $image_src, $image_meta, $attachment_id );
Changelog
Version | Description |
---|---|
5.5.0 | Introduced. |
User Contributed Notes
You must log in before being able to contribute a note or feedback.