Responsive Images – Add srcset attributes to custom Images Function

When I use get_the_post_thumbnail( NULL, 'entry-fullwidth', NULL ); wordpress automatically outputs the srcset data like these:

<img 
    width="1000" 
    height="625" 
    src="https://x.cloudfront.net/wp-content/uploads/2017/08/photo.jpg" 
    class="attachment-entry-fullwidth size-entry-fullwidth wp-post-image" 
    alt="" 
    srcset="
        https://x.cloudfront.net/wp-content/uploads/2017/08/photo.jpg 1000w, 
        https://x.cloudfront.net/wp-content/uploads/2017/08/photo-768x480.jpg 768w" 
    sizes="
        (max-width: 767px) 95vw, 
        (max-width: 979px) 80vw, 1200px
">

Is there a native wordpress function or another way to output srcset data for images in my custom function below?

function photo_shortcode($atts){
   extract(shortcode_atts(array(
      'no' => 1,
   ), $atts));

   $no     = ( $no       != ''     ) ? $no : 1;
   $images = get_field('fl_gallery');
   $image  = $images[$no];

if ($image) {
   $credit = get_field('fl_credit', $image['id']);
   return '<div class="kalim"><img title="' . esc_attr( sprintf( the_title_attribute( 'echo=0' ) ) ) . '" alt="' . esc_attr( sprintf( the_title_attribute( 'echo=0' ) ) ) . '" src="' . $image['url'] . '" /><div class="kalca">' . $image['caption'] . '</div>' . (!empty($credit) ? '<div class="kalcr">Credit:' . $credit . '</div></div>': '' ) ;
 }

}

add_shortcode('photo', 'photo_shortcode');

2 Answers
2

I think wp_get_attachment_srcset() is what you are looking for.

$srcset = wp_get_attachment_image_srcset( $image['id'], array( 100, 100 ) );

Now you can escape the HTML and use it in your code.

<img src="https://wordpress.stackexchange.com/questions/276972/PATH HERE" srcset="https://wordpress.stackexchange.com/<?php echo esc_attr( $srcset ); ?>">

Leave a Comment