read

Recently while working on a side project, I was looking for a quick and easy solution to turn post-thumbnails in Wordpress into responsive images. Specifically I wanted to implement it using the srcset & sizes attributes on an <img>-tag. You can read more about how and why to use that syntax in Eric Portis' great Article Srcset and sizes.

My Google search didn't deliver a satisfying solution for my problem. Most results pointed to the Responsive Images wordpress plugin by RICG. Which is great for making images in posts responsive, but doesn't help you with using post-thumbnails in your wordpress theme.

Then I found this article which nearly solves my problem - BUT uses the picture-element instead of the more practical srcset & sizes.

My solution

So at least now I had a good starting point to write my own wordpress function. Since I'm no adept php developer there surely is room for improvement, but it works for me.

Usage Example:

<?php 
echo crohrer_responsive_post_thumbnail(
    get_the_ID(), // Post ID
    '(min-width: 940px) 300px, (min-width: 500px) calc((100vw - 20px) * 0.33), 100vw', // sizes attribute
    array('gallery', 'gallery-retina-small', 'gallery-retina'), // list of thumnail sizes
    '', // alt attribute for img
    'attachment-gallery wp-post-image' // classnames for img
); 
?>

You can see it in action at my friends gallery page.

Features:

  • Creates a valid <img>-tag with srcset & sizes, using different image sizes generated by Wordpress
  • Defaults to fill the srcset attribute with all available thumbnail sizes – or lets you choose which sizes you want to use & checks if that size exists for your image. (Be aware that some thumnail sizes are cropped. Mixing different aspect ratios in one srcset may lead to unexpected results)
  • Defaults to fill the sizes attribute with 100vh – You will really want to change that to something more specific in most cases.
  • The sources in srcset are listed in ascending order by width
  • the src attribute is filled with the smallest image for mobile first legacy browser support

If you want to use it, consider including picturefill to fully support older browsers. But don't worry, it degrades gracefully without it.

Blog Logo

Christoph Rohrer


Published

Image

Collecting Experience

Back to Overview