Skip to content

Instantly share code, notes, and snippets.

@joshuafredrickson
Created January 20, 2020 17:56
Show Gist options
  • Save joshuafredrickson/206680b69e06541122d4c7e5865b6946 to your computer and use it in GitHub Desktop.
Save joshuafredrickson/206680b69e06541122d4c7e5865b6946 to your computer and use it in GitHub Desktop.
Quick and dirty responsive <picture> component for ACF images
{{--
$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>
<?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;
}
@joshuafredrickson
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment