Roots Discourse

Getting the URL of a spefific image size, with srcset (Slick Slider + ACF)

sage9

#1

After finally finishing setting up a Slick Slider with Gutenberg blocks, I noticed that my slides were very fuzzy. Since I am using the “large” size for my images, I noticed that the srcset was not generated at all and somehow created this fuzzyness to my images. Here is the code:

<?php $images = get_field('slider'); if( $images ): ?>
  <div class="slick-slider">
    <?php foreach( $images as $image ): ?>
      <?php $img_url = wp_get_attachment_image_src($image['id'], 'large'); ?>
      <div>
        <img class="slick-image" src="<?php echo $img_url[0] ?>" alt="<?php echo $image['alt']; ?>">
      </div>
    <?php endforeach; ?>
  </div>
<?php endif; ?>

Now I am aware that the Sage 9 book is explaining how to deal with srcset and wp_get_attachment_image_src with specific size. However, I don’t understand how to make it work considering that I am not working with a post thumbnail but with a variable related to my slider and Advanced Custom Field.

Please help me! I’m trying super hard to understand how all these things works. Thanks :slight_smile:


#2

You aren’t defining a srcset attribute in the <img> tag you’re generating. That’s why you don’t have a srcset. This code seems a little overengineered: you’re building an image manually when you could just have WordPress do it for you and get the srcset automatically:

<?php if( $images = get_field('slider') ): ?>
  <div class="slick-slider">
    <?php foreach( $images as $image ): ?>
      <div>
        <?php echo wp_get_attachment_image(
          $image['id'], 
          'large',
          false,
          ['class' => 'slick-image']); ?>
      </div>
    <?php endforeach; ?>
  </div>
<?php endif; ?>

I’d recommend looking at the documentation for wp_get_attachment_image(): https://developer.wordpress.org/reference/functions/wp_get_attachment_image/