diff --git a/src/wp-includes/media.php b/src/wp-includes/media.php index 9cf301e95c..38ec2213b7 100644 --- a/src/wp-includes/media.php +++ b/src/wp-includes/media.php @@ -2117,6 +2117,13 @@ function wp_img_tag_add_width_and_height_attr( $image, $context, $attachment_id $size_array = wp_image_src_get_dimensions( $image_src, $image_meta, $attachment_id ); if ( $size_array ) { + // If the width is enforced through style (e.g. in an inline image), calculate the dimension attributes. + $style_width = preg_match( '/style="width:\s*(\d+)px;"/', $image, $match_width ) ? (int) $match_width[1] : 0; + if ( $style_width ) { + $size_array[1] = (int) round( $size_array[1] * $style_width / $size_array[0] ); + $size_array[0] = $style_width; + } + $hw = trim( image_hwstring( $size_array[0], $size_array[1] ) ); return str_replace( 'attachment->create_upload_object( $file ); + self::$attachment_width = 680; + self::$attachment_height = 1024; + } + + public static function tear_down_after_class() { + wp_delete_attachment( self::$attachment_id, true ); + parent::tear_down_after_class(); + } + + /** + * Tests that `wp_img_tag_add_width_and_height_attr()` adds dimension attributes to an image when they are missing. + * + * @ticket 50367 + */ + public function test_add_width_and_height_when_missing() { + $image_tag = ''; + + $this->assertSame( + '', + wp_img_tag_add_width_and_height_attr( $image_tag, 'the_content', self::$attachment_id ) + ); + } + + /** + * Tests that `wp_img_tag_add_width_and_height_attr()` does not add dimension attributes when disabled via filter. + * + * @ticket 50367 + */ + public function test_do_not_add_width_and_height_when_disabled_via_filter() { + add_filter( 'wp_img_tag_add_width_and_height_attr', '__return_false' ); + $image_tag = ''; + + $this->assertSame( + $image_tag, + wp_img_tag_add_width_and_height_attr( $image_tag, 'the_content', self::$attachment_id ) + ); + } + + /** + * Tests that `wp_img_tag_add_width_and_height_attr()` does not add dimension attributes to an image without src. + * + * @ticket 50367 + */ + public function test_do_not_add_width_and_height_without_src() { + $image_tag = ''; + + $this->assertSame( + $image_tag, + wp_img_tag_add_width_and_height_attr( $image_tag, 'the_content', self::$attachment_id ) + ); + } + + /** + * Tests that `wp_img_tag_add_width_and_height_attr()` respects the style attribute from the inline image format to + * correctly set width and height based on that. + * + * @ticket 59352 + */ + public function test_consider_inline_image_style_attr_to_set_width_and_height() { + // '85px' is the original width (680px) divided by 8, so the expected height is equivalently 1024/8=128. + $image_tag = ''; + + $this->assertSame( + '', + wp_img_tag_add_width_and_height_attr( $image_tag, 'the_content', self::$attachment_id ) + ); + } +}