1

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

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="PATH HERE" srcset="<?php echo esc_attr( $srcset ); ?>">
  • ok but that is the array( 100, 100 ) used for? The answer should return the url for the 768x400 size ? – Joanna Mikalai Aug 15 '17 at 16:16
  • That was just an example. You can use any size you wish, or even pass a size slug such as medium or large. – Jack Johansson Aug 15 '17 at 16:24
0

Take a look of this article https://alexwright.net/web-design-secrets/responsive-images-wordpress/

It explains how srcset and responsive images work in Wordpress.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.