Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't apply auto-sizes if there is no width and add filter for disabling #7812

Closed
25 changes: 23 additions & 2 deletions src/wp-includes/media.php
Original file line number Diff line number Diff line change
Expand Up @@ -1137,8 +1137,12 @@ function wp_get_attachment_image( $attachment_id, $size = 'thumbnail', $icon = f
}
}

/** This filter is documented in wp-includes/media.php */
$add_auto_sizes = apply_filters( 'wp_img_tag_add_auto_sizes', true );

// Adds 'auto' to the sizes attribute if applicable.
felixarntz marked this conversation as resolved.
Show resolved Hide resolved
if (
$add_auto_sizes &&
isset( $attr['loading'] ) &&
'lazy' === $attr['loading'] &&
isset( $attr['sizes'] ) &&
Expand Down Expand Up @@ -1985,6 +1989,17 @@ 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.
*/
if ( ! apply_filters( 'wp_img_tag_add_auto_sizes', true ) ) {
return $image;
}

$processor = new WP_HTML_Tag_Processor( $image );

// Bail if there is no IMG tag.
Expand All @@ -1993,8 +2008,14 @@ function wp_img_tag_add_auto_sizes( string $image ): string {
}

// Bail early if the image is not lazy-loaded.
$value = $processor->get_attribute( 'loading' );
if ( ! is_string( $value ) || 'lazy' !== strtolower( trim( $value, " \t\f\r\n" ) ) ) {
$loading = $processor->get_attribute( 'loading' );
if ( ! is_string( $loading ) || 'lazy' !== strtolower( trim( $loading, " \t\f\r\n" ) ) ) {
return $image;
}

// Bail early if the image doesn't have a width attribute.
$width = $processor->get_attribute( 'width' );
if ( ! is_string( $width ) ) {
Comment on lines +2012 to +2018
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could consolidate these two if statements, but left it for readability.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it possible for $width to be an empty string here? Perhaps empty( $width ) || ! is_string( $width ) may be better.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in baee465

return $image;
}

Expand Down
Loading
Loading