Skip to content

Preserve custom image sizes attributes ​

Optimole's WordPress plugin can preserve an image's existing sizes attribute instead of adding measured breakpoints to it. The sizes attribute tells the browser how much space an image is expected to take at different screen widths. This markup and filter feature is separate from the Smart Image Scaling setting.

In this article

Preserve sizes for one image ​

Add the boolean data-optml-keep-sizes attribute to an image that already has a sizes value:

html
<img src="https://example.com/photo.jpg"
     srcset="https://example.com/photo-600.jpg 600w, https://example.com/photo.jpg 1200w"
     sizes="(max-width: 600px) 100vw, 600px"
     data-optml-keep-sizes
     alt="Example photo">

Optimole leaves the existing sizes value unchanged. It can still add or enhance the srcset attribute, which lists image candidates the browser can choose from.

Preserve existing sizes site-wide ​

To preserve existing sizes attributes on all images, add this PHP snippet through a PHP snippets plugin or your child theme's functions.php file:

php
add_filter( 'optml_keep_existing_sizes', '__return_true' );

The optml_keep_existing_sizes filter receives two arguments: $keep, a boolean that is true when the image has the data-optml-keep-sizes attribute, and $tag, the image-tag string. A custom callback can inspect $tag and return true only for selected images. Returning false overrides the per-image opt-in. Optimole's other normal checks still apply.

This preserves an existing sizes attribute; it does not prevent Optimole from generating one when it is missing.

Lazy-loading limitation ​

Images lazy-loaded by Optimole do not retain srcset or sizes, because Optimole's lazy loader does not need them. Neither the per-image attribute nor the filter disables lazy loading or makes those images retain these attributes. Use this preservation option for images that are not lazy-loaded by Optimole.

Was this helpful?