Created
June 1, 2015 06:13
-
-
Save simme/e2171e7c7a717d3844c5 to your computer and use it in GitHub Desktop.
Responsive images wordpress
This file contains hidden or 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
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