Created
January 20, 2020 17:56
-
-
Save joshuafredrickson/206680b69e06541122d4c7e5865b6946 to your computer and use it in GitHub Desktop.
Quick and dirty responsive <picture> component for ACF images
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
{{-- | |
$image: ACF image field | |
$images: \App\get_image_sizes($image_id) | |
$class | |
$alt | |
$width: Optionally define how wide this image should be at different breakpoints | |
--}} | |
<picture class="acf-image {{ $class ?? '' }}"> | |
<source srcset=" | |
@foreach($images as $key => $value) | |
{{ $value['url']}} {{ $value['width'] }}w, | |
@endforeach | |
" {!! !empty($width) ? 'sizes="(max-width: 640px) 100vw, ' . $width . '"' : '' !!} | |
> | |
<img src="{{ $image['sizes']['9/12'] }}" | |
alt="{{ $alt ?? $image['alt'] }}" | |
> | |
</picture> |
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
<?php | |
/** | |
* Get responsive image attributes | |
* | |
* @return array|false | |
*/ | |
function get_image_sizes($id = false) | |
{ | |
if (!$id) { | |
return; | |
} | |
// Get all registered image sizes | |
$image_sizes = get_intermediate_image_sizes(); | |
$skip_sizes = ['thumbnail', 'medium', 'medium_large', 'large']; // Skip WP defaults | |
$images = []; | |
collect($image_sizes)->map(function ($size) use ($id, $skip_sizes, &$images) { | |
if (in_array($size, $skip_sizes)) { | |
return; | |
} | |
$image = wp_get_attachment_image_src($id, $size); | |
$images[$size] = [ | |
'url' => $image[0], | |
'width' => $image[1], | |
'height' => $image[2], | |
]; | |
return; | |
}); | |
return $images; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Reference: https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images