I've limited the image sizes output by wp_get_attachment_image_srcset()
to 768 pixels (by default they are limited to 1600 pixels):
function set_max_srcset_image_width( $max_srcset_image_width, $sizes_array ) {
return 768;
}
add_filter( 'max_srcset_image_width', 'set_max_srcset_image_width', 10, 2 );
However, I have one image where I would like to revert back to the default of 1600 max.
Since the max_srcset_image_width
filter doesn't include any additional arguments to identify an image or the fact that you might want to override the max size, I can't figure out how to do this. At the moment it means either all of my images include too big a size, or one of my images is too small.
I resolved this as follows:
// Limit srcset images to 768 pixels
function set_max_srcset_image_width( $max_srcset_image_width, $sizes_array ) {
return 768;
}
add_filter( 'max_srcset_image_width', 'set_max_srcset_image_width', 10, 2 );
Then when I have an image where I want to include the 1,600 version and ignore the 768 maximum, I did this:
<img srcset="<?php echo wp_get_attachment_image_srcset( $attachment_id, 'large' ); ?>" />
Where large
is the 1600 pixel version.
I could never figure out what the second parameter in wp_get_attachment_image_srcset()
was for because it never seemed to restrict the function to outputting a maximum or minimum size. However in the example here it does what I want.