Home > other >  WordPress not outputting srcset and sizes attr in img tag
WordPress not outputting srcset and sizes attr in img tag

Time:07-14

Weird problem: I have a function:

function mytheme_get_responsive_image( $image_id ) {
        $size   = 'full';
        $src    = wp_get_attachment_image_url( $image_id, $size );
        $class  = 'myclass';
        $alt    = get_post_meta( $image_id, '_wp_attachment_image_alt', true );
        $srcset = wp_get_attachment_image_srcset( $image_id, $size );
        $sizes  = '(min-width: 1200px) 354px, (max-width: 767px) 87vw, (max-width: 1024px) 52.2vw, (max-width: 1199px) 27.45vw';

        $output  = '<img src="' . esc_attr( $src ) . '" ';
        $output .= 'alt="' . esc_attr( $alt ) . '" ';
        $output .= ' ';
        $output .= 'srcset="' . esc_attr( $srcset ) . '" ';
        $output .= 'sizes="' . esc_attr( $sizes ) . '">';

        return $output;
}

When I write the result of $output to a logfile it says:

<img src="https://local.test/wp-content/uploads/2022/04/picture.jpg" alt="alttext"  srcset="https://local.test/wp-content/uploads/2022/04/picturejpg 1000w, https://local.test/wp-content/uploads/2022/04/picture.jpg 300w, https://local.test/wp-content/uploads/2022/04/picture.jpg 768w" sizes="(min-width: 1200px) 354px, (max-width: 767px) 87vw, (max-width: 1024px) 52.2vw, (max-width: 1199px) 27.45vw">

That's exactly what I wanted.

But when I output the image in the sidebar:

echo mytheme_get_responsive_image( $image_id );

then that's what I get in the final code:

<img src="https://local.test/wp-content/uploads/2022/04/picture.jpg" alt="alttext" >

The scrset and sizes attributes are not being outputted.

What could be the reason?

CodePudding user response:

I figured it out:

The problem was that I sanitized the complete sidebar afterwards with wp_kses_post(). And this is stripping out the srcset and sizes attributes from the <img> tag.

There is a ticket from 8 years ago describing this problem: https://core.trac.wordpress.org/ticket/29807

  • Related