Skip to content

Instantly share code, notes, and snippets.

@lgladdy
Created July 18, 2016 10:36
Show Gist options
  • Save lgladdy/c1f7e42a23fe7b62643801bbabd34256 to your computer and use it in GitHub Desktop.
Save lgladdy/c1f7e42a23fe7b62643801bbabd34256 to your computer and use it in GitHub Desktop.
function get_responsive_image_tag_for_attachment($attachment_id, $requested_size) {
$data = get_responsive_image_sizes_for_size($requested_size);
$srcset = [];
foreach($data as $image) {
$image_data = wp_get_attachment_image_src($attachment_id, $image);
if ($requested_size == $image) {
$src = $image_data[0];
}
$srcset[] = $image_data[0].' '.$image_data[1].'w';
}
$image_tag = '<img srcset="';
$image_tag .= implode($srcset, ', ');
$image_tag .= '" src="'.$src.'" />';
return $image_tag;
}
function responsive_image_tag_for_attachment($attachment_id, $requested_size) {
echo get_responsive_image_tag_for_attachment($attachment_id, $requested_size);
}
function get_responsive_image_sizes_for_size($requested_size) {
$sizes = get_intermediate_image_sizes();
$return = [];
foreach($sizes as $size) {
if (substr($size, 0, strlen($requested_size)) === $requested_size) $return[] = $size;
}
return $return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment