Instantly share code, notes, and snippets.

Embed
What would you like to do?
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