10

I am trying to use the new responsive images feature in Wordpress 4.4 but I keep running into a particular problem when trying to use the_post_thumbnail with a custom image size. It seems I cannot use custom image sizes.

The following code will produce an img tag with the srcset present:

<?php the_post_thumbnail('medium',  array( 'class' => 'img-responsive' )); ?>

Here is what the img tag looks like with the medium size passed into the function:

<img width="300" height="225" src="path/to/image-300x225.jpg" class="img-responsive wp-post-image" alt="Image" srcset="path/to/image-300x225.jpg 300w, path/to/image-768x576.jpg 768w, path/to/image.jpg 1024w" sizes="(max-width: 300px) 100vw, 300px">

However, when I make one change to use my custom image size, the srcset disappears. Does anyone know what is going on here?

Here is how I added my custom image size:

add_image_size ('my-custom-size', 1050, 626, true );

Here is how it looks in the code:

<?php the_post_thumbnail('my-custom-size',  array( 'class' => 'img-responsive' )); ?>

And here is what it outputs, notice that my-custom-size is not being read and it is instead adding in wp-post-image instead of my-custom-size:

<img width="1024" height="626" src="path/to/image-1024x626.jpg" class="img-responsive wp-post-image" alt="Image">

Please help me understand what I am doing wrong!

4
  • 1
    set yours add_image_size ('my-custom-size', 1050, 0, false ); and for the explanation, please read this answered wordpress.stackexchange.com/a/211405/18731
    – Jevuska
    Mar 12, 2016 at 4:19
  • Did you test with a freshly uploaded image? Your new image size will only be applied when images are uploaded. You can regenerate image sets for your existing images using a plugin like Regenerate Thumbnails. May 19, 2016 at 12:27
  • 1
    @Jevuska that won't hard crop the image to the dimensions that the questioner wants though. May 19, 2016 at 12:29
  • 1
    Did my answer help at all? Is this question still current? Aug 4, 2016 at 18:50

1 Answer 1

8

There's not enough info to be sure this answer is definitive but here's an attempt.

Firstly make sure the image you are uploading is actually larger than the size you have defined. I see people upload images that are too small and then get this sort of result all the time.

Secondly, WP will only make up a Srcset list of image sizes with the same aspect ratio. If your custom size had a different aspect ratio to other image sizes then you can create a selection of new sizes with aspect ratios that match.

Thirdly, after changing or adding new image sizes you must always regenerate existing thumbnails. There's a great plugin called Regenerate Thumbnails for this.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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