Skip to content

Commit

Permalink
Add filter for enabling auto-sizes functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
joemcgill committed Nov 15, 2024
1 parent 3cfcbe2 commit e45b275
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/wp-includes/media.php
Original file line number Diff line number Diff line change
Expand Up @@ -1975,6 +1975,18 @@ function wp_filter_content_tags( $content, $context = null ) {
* @return string The filtered image tag markup.
*/
function wp_img_tag_add_auto_sizes( string $image ): string {
/**
* Filters whether auto-sizes for lazy loaded images is enabled.
*
* @since 6.7.1
*
* @param boolean $enabled Whether auto-sizes for lazy loaded images is enabled.
* @param string $image The image tag markup being modified.
*/
if ( ! apply_filters( 'wp_image_tag_auto_sizes_enabled', true, $image ) ) {
return $image;
}

$processor = new WP_HTML_Tag_Processor( $image );

// Bail if there is no IMG tag.
Expand Down
40 changes: 40 additions & 0 deletions tests/phpunit/tests/media.php
Original file line number Diff line number Diff line change
Expand Up @@ -6266,6 +6266,46 @@ public function test_content_image_without_lazy_loading_does_not_have_auto_sizes
);
}

/**
* Test content filtered markup with lazy loading does not get auto-sizes when disabled.
*
* @ticket 61847
* @ticket 62413
*
* @covers ::wp_img_tag_add_auto_sizes
*/
public function test_content_image_does_not_have_auto_sizes_when_disabled() {
// Force lazy loading attribute.
add_filter( 'wp_img_tag_add_loading_attr', '__return_true' );
// Disable auto-sizes attribute.
add_filter( 'wp_image_tag_auto_sizes_enabled', '__return_false' );

$this->assertStringNotContainsString(
'sizes="auto, ',
wp_filter_content_tags( get_image_tag( self::$large_id, '', '', '', 'large' ) ),
'Failed asserting that the sizes attribute for a content image with lazy loading does not include "auto" when disabled.'
);
}

/**
* Test generated image markup with lazy loading does not get auto-sizes when disabled.
*
* @ticket 61847
* @ticket 62413
*
* @covers ::wp_img_tag_add_auto_sizes
*/
public function test_generated_image_does_not_have_auto_sizes_when_disabled() {
// Disable auto-sizes attribute.
add_filter( 'wp_image_tag_auto_sizes_enabled', '__return_false' );

$this->assertStringNotContainsString(
'sizes="auto, ',
wp_get_attachment_image( self::$large_id, 'large', false, array( 'loading' => 'lazy' ) ),
'Failed asserting that the sizes attribute for an image with lazy loading does not include "auto" when disabled.'
);
}

/**
* Test generated markup for an image with 'auto' keyword already present in sizes does not receive it again.
*
Expand Down

0 comments on commit e45b275

Please sign in to comment.