Skip to content

Instantly share code, notes, and snippets.

@crohrer
Last active June 13, 2016 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save crohrer/a061c460b3811eb88b54 to your computer and use it in GitHub Desktop.
Save crohrer/a061c460b3811eb88b54 to your computer and use it in GitHub Desktop.
responsive thumbnails for wordpress
/*
* crohrer_responsive_post_thumbnail
*
* @author: Christoph Rohrer
*
*/
function crohrer_responsive_post_thumbnail( $post_id, $sizesAttribute = '100vw', $thumbnailSizes = array(), $alt = '', $class = '' )
{
$postThumbnailId = get_post_thumbnail_id( $post_id );
if(empty($thumbnailSizes)){
$thumbnailSizes = get_intermediate_image_sizes(); // fallback to all available sizes
}
$srcsets = array();
$thumbnails = array();
foreach ($thumbnailSizes as $thumbnailSize){
$thumbnail = wp_get_attachment_image_src($postThumbnailId, $thumbnailSize );
// only use properly resized images
if($thumbnail[3]){
$thumbnails[$thumbnailSize] = $thumbnail[1];
$srcsets[$thumbnail[1]] = $thumbnail[0].' '.$thumbnail[1].'w';
}
}
ksort($srcsets);
$smallestSize = array_keys($thumbnails, min($thumbnails))[0];
$image = '<img src="'.wp_get_attachment_image_src($postThumbnailId, $smallestSize)[0].'"';
$image .= ' alt="'.$alt.'"';
$image .= (!empty($class)) ? ' class="'.$class.'"' : '';
$image .= ' srcset="'.implode(', ', $srcsets).'"';
$image .= ' sizes="'.$sizesAttribute.'"/>';
return $image;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment