Home / Attachments / Add Auto Sizes to Lazy Loaded images
Duplicate Snippet

Embed Snippet on Your Site

Add Auto Sizes to Lazy Loaded images

Use the "auto" size added in browsers for lazy loaded images.

400+
Code Preview
php
<?php
add_filter( 'wp_get_attachment_image_attributes', function( $attr ) {
	if ( ! isset( $attr['loading'] ) || 'lazy' !== $attr['loading'] || ! isset( $attr['sizes'] ) ) {
		return $attr;
	}
	
	// Skip if attribute was already added.
	if ( false !== strpos( $attr['sizes'], 'auto,' ) ) {
		return $attr;
	}
	$attr['sizes'] = 'auto, ' . $attr['sizes'];
	return $attr;
} );
add_filter( 'wp_content_img_tag',  function( $html ) {
	if (false === strpos($html, 'loading="lazy"') || (false === strpos($html, 'sizes="') || false !== strpos($html, 'sizes="auto,'))) {
		return $html;
	}
	$html = str_replace( 'sizes="', 'sizes="auto, ', $html );
	return $html;
} );

Comments

Add a Comment