Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions src/wp-includes/media.php
Original file line number Diff line number Diff line change
Expand Up @@ -1153,8 +1153,12 @@ function wp_get_attachment_image( $attachment_id, $size = 'thumbnail', $icon = f
unset( $attr['fetchpriority'] );
}

// Generate 'srcset' and 'sizes' if not already present.
if ( empty( $attr['srcset'] ) ) {
// If srcset is set to false, it should be omitted.
if ( isset( $attr['srcset'] ) && false === $attr['srcset'] ) {
unset( $attr['srcset'] );
unset( $attr['sizes'] );
} elseif ( empty( $attr['srcset'] ) ) {
// Generate 'srcset' and 'sizes' if not already present and srcset is not set to false.
$image_meta = wp_get_attachment_metadata( $attachment_id );

if ( is_array( $image_meta ) ) {
Expand All @@ -1170,6 +1174,12 @@ function wp_get_attachment_image( $attachment_id, $size = 'thumbnail', $icon = f
}
}
}

// If after trying to generate it, it's still empty, omit it.
if ( empty( $attr['srcset'] ) ) {
unset( $attr['srcset'] );
unset( $attr['sizes'] );
}
}

/** This filter is documented in wp-includes/media.php */
Expand Down
22 changes: 22 additions & 0 deletions tests/phpunit/tests/media/wpGetAttachmentImage.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

/**
* @group media
*/
class Tests_Media_WpGetAttachmentImage extends WP_UnitTestCase {

/**
* @ticket 43070
*/
public function test_wp_get_attachment_image_should_not_include_sizes_when_srcset_is_disabled() {
$file = DIR_TESTDATA . '/images/canola.jpg';
$attachment_id = $this->factory->attachment->create_upload_object( $file, 0 );

$html = wp_get_attachment_image( $attachment_id, 'thumbnail', false, array( 'srcset' => false ) );

wp_delete_attachment( $attachment_id, true );

$this->assertStringNotContainsString( 'srcset=', $html, 'The srcset attribute should not be rendered.' );
$this->assertStringNotContainsString( 'sizes=', $html, 'The sizes attribute should not be rendered when srcset is absent.' );
}
}
Loading