I'm trying to modify the default 'sizes' attribute for images placed in content using the default WP sizes (e.g., Medium or Large). These are images generally placed in the body of a page/post with text wrapping, but rarely end up requiring the default sizes listed (e.g., 100vw up to image width, then static image width) in a responsive layout. Need something more realistic.

Here's what I use on other projects when using custom generated sizes. This does not appear to work with the default image size naming I've added though:

function my_attachment_image_attributes( $attr, $attachment, $size ) {
if ( $size === 'medium' ) {
    $attr['sizes'] = '(max-width: 375px) 100vw, (max-width: 767px) 31vw, 240px';
} elseif ( $size === 'large' ) {
    $attr['sizes'] = '(max-width: 520px) 100vw, (max-width: 767px) 60vw, 400px';
return $attr;
add_filter( 'wp_get_attachment_image_attributes','my_attachment_image_attributes', 10, 3 );

This is what I have working, and while close, fails on portrait-oriented images whose width won't be as large as it needs to be to trigger properly.

function my_content_image_sizes_attr( $sizes, $size ) {
    $width = $size[0];
        400 >= $width && 240 < $sizes = '(max-width: 520px) 100vw, (max-width: 767px) 60vw, 400px';
        240 >= $width && $sizes = '(max-width: 375px) 100vw, (max-width: 767px) 31vw, 240px';
add_filter( 'wp_calculate_image_sizes', 'my_content_image_sizes_attr', 10 , 2 );
  • Any ideas on how to get something working based on the default image size applied (e.g., Medium or Large) rather than a specified width/width-range??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.