Last active
June 13, 2016 21:17
-
-
Save crohrer/a061c460b3811eb88b54 to your computer and use it in GitHub Desktop.
responsive thumbnails for wordpress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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