Skip to content

Instantly share code, notes, and snippets.

@uhlhosting
Created January 17, 2022 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uhlhosting/c2615055cfb8e543ce960f53ee146089 to your computer and use it in GitHub Desktop.
Save uhlhosting/c2615055cfb8e543ce960f53ee146089 to your computer and use it in GitHub Desktop.
srcset for Wordpress post thumbnails
<?php
function srcset_post_thumbnail($defaultSize = 'medium')
{
// those are the default thumbnail sizes for wordpress.
// we can -and should- define our own sizes according to our breakpoints
$thumbnailSizes = [
'thumbnail',
'medium',
'large',
'full'
];
// here, we add our breakpoints as detailed in https://css-tricks.com/video-screencasts/133-figuring-responsive-images/
// thanks @chriscoyier
$html = '<img sizes="';
$html .= '(max-width: 30em) 100vw, ';
$html .= '(max-width: 50em) 50vw, ';
$html .= 'calc(33vw - 100px)" ';
$html .= 'srcset="';
$thumb_id = get_post_thumbnail_id();
for ($i = 0; $i < count($thumbnailSizes); $i++) {
$thumb = wp_get_attachment_image_src($thumb_id, $thumbnailSizes[$i], true);
$url = $thumb[0];
$width = $thumb[1];
$html .= $url . ' ' . $width . 'w';
if ($i < count($thumbnailSizes) - 1) {
$html .= ', ';
}
}
$alt = get_post_meta($thumb_id, '_wp_attachment_image_alt', true);
$thumbMedium = wp_get_attachment_image_src($thumb_id, $defaultSize, true);
$html .= '" ';
$html .= 'src="' . $thumbMedium[0] . '" alt="' . $alt . '">';
return $html;
}
// we can output our srcset post-thumbnail via the function srcset_post_thumbnail($size);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment