Skip to content

Instantly share code, notes, and snippets.

@simme
Created June 1, 2015 06:13
Show Gist options
  • Save simme/e2171e7c7a717d3844c5 to your computer and use it in GitHub Desktop.
Save simme/e2171e7c7a717d3844c5 to your computer and use it in GitHub Desktop.
Responsive images wordpress
function lpg_get_attachment( $attachment_id ) {
$attachment = get_post( $attachment_id );
return array(
'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
'caption' => $attachment->post_excerpt,
'description' => $attachment->post_content,
'href' => get_permalink( $attachment->ID ),
'src' => $attachment->guid,
'title' => $attachment->post_title
);
}
/**
* Generate responsive image
*
* Generates a responsive image tag (using srcset) for the given attachment ID
* using the given thumbnail sizes matching the given media queries (sizes).
* Default image will be the first size given.
*/
function lpg_srcset($id, $sizes, $mq, $classes) {
$meta = lpg_get_attachment($id);
$images = [];
foreach ($sizes as $size) {
$images[] = wp_get_attachment_image_src($id, $size);
}
return sprintf(
'<img src="%s" sizes="%s" srcset="%s" alt="%s" width="%d" height="%d" class="%s">',
'', //$images[0][0], // ** Source omitted for picturefill polyfill
join($mq, ','),
join(array_map(function ($x) { return $x[0] . ' ' . $x[1] . 'w'; }, $images), ','),
$meta['alt'],
$images[0][1],
$images[0][2],
join($classes, ' ')
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment