I have this function in my theme to create thumbnail sizes.
set_post_thumbnail_size( 620, 848, true );
if (function_exists('add_image_size')){
add_image_size( 'compare-shop-logo', 150 );
add_image_size( 'compare-single-product-2', 250, 188, true );
add_image_size( 'compare-slider-image', 848, 487, true );
add_image_size( 'compare-offer-box', 400, 300, true);
add_image_size( 'compare-blog-box', 400, 225, true );
add_image_size( 'compare-quote-box', 408, 437, true );
}
How come that if I change the offer-box sizes, I lose the srcset and sizes in img tag? and is there a way to resize maintaining proportions?
<img width="400" height="300" src="https://wordpress.stackexchange.com/questions/241905/myimage-400x300.jpg" class="embed-responsive-item wp-post-image" alt="image" srcset="myimage-1-400x300.jpg 400w, http:///myimage-250x188.jpg 250w" sizes="(max-width: 400px) 100vw, 400px">
thanks
The srcset attribute is constructed from images that are the same aspect ratio. Create a few of those and you’ll be ok.
add_image_size( 'compare-offer-box', 400, 300, true);
add_image_size( 'compare-offer-box-2', 800, 600, true);
add_image_size( 'compare-offer-box-3', 1200, 900, true);
for example. The fourth, boolean, argument tells WP to crop to the exact proportions.
To resize without cropping, use:
add_image_size( 'compare-offer-box', 400, 9999, false);
add_image_size( 'compare-offer-box-2', 800, 9999, false);
add_image_size( 'compare-offer-box-3', 1200, 9999, false);
This assumes you want a particular width image and then whatever height the proportions require. You’ll see some code around the web that uses values of 0
or null
for the non-constrained dimension, but comments in the WP source code warn that this can have “unpredictable results.”
If you’d rather scale proportionately while constraining the height then just use a huge value for the width:
add_image_size( 'compare-offer-box', 9999, 400, false);
add_image_size( 'compare-offer-box-2', 9999, 800, false);
add_image_size( 'compare-offer-box-3', 9999, 1200, false);
If you want to maintain proportions but scale the image to fit within a certain space, say 400px by 400px, you can specify both maximum width and height but with cropping set to false:
add_image_size( 'compare-offer-box', 400, 400, false);
Note that if you are constraining by height then you may want to adjust the sizes attribute too, as that defaults to the width of the viewport with a maximum value of the specified image size’s width.
Don’t forget that you’ll then need to regenerate image sizes for your existing images. There are plugins that do this well: Search for Regenerate Thumbnails in the plugin repository.