Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Accudio
Last active January 26, 2022 15:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Accudio/e7aae5823018bbedff4c9868c1241a3d to your computer and use it in GitHub Desktop.
Save Accudio/e7aae5823018bbedff4c9868c1241a3d to your computer and use it in GitHub Desktop.
Example Advanced Custom Fields abstraction of an Image CDN. Built with CloudImage and an alias in mind, customise as your setup and provider.
<?php
echo image( [
'image' => get_field('image'),
'srcset' => [300, 450, 600, 800, 1000, 1200],
'sizes' => '100vw',
'loading' => 'lazy'
'class' => 'image-class'
] );
<?php
define( 'CDN_BASE', 'https://example.imagecdn.com' );
function image ( $args = [] ) {
if ( !$args['image'] ) {
return;
}
// set defaults here
$defaults = [
'alt' => '',
'srcset' => [ 300, 450, 600, 800, 1000, 1200 ],
'sizes' => '(min-width: 82rem) 80rem, calc(100vw - 2rem)',
'loading' => 'lazy',
'class' => false,
'picClass' => false,
'lowdpiQuality' => 80,
'hidpiQuality' => 40
];
$opts = array_merge( $defaults, $args );
$src = explode( '/uploads', $args['image']['url'] )[1];
$fallback = create_src(
$src,
$opts['srcset'][count($opts['srcset']) - 1],
$opts['lowdpiQuality']
);
$srcset = create_srcset( $src, $opts['srcset'], $opts['lowdpiQuality'] );
$hidpi_srcset = create_srcset( $src, $opts['srcset'], $opts['hidpiQuality'] );
$markup = sprintf(
'<picture %s>
<source media="(-webkit-min-device-pixel-ratio: 1.5)" srcset="%s" sizes="%s">
<img %s alt="%s" src="%s" srcset="%s" sizes="%s" width="%s" height="%s" loading="%s" decoding="async">
</picture>',
$opts['picClass'] ? ('class="' . $opts['picClass'] . '"') : '',
$hidpi_srcset,
$opts['sizes'],
$opts['class'] ? ('class="' . $opts['class'] . '"') : '',
$opts['alt'] ? $opts['alt'] : $args['image']['alt'],
$fallback,
$srcset,
$opts['sizes'],
$opts['image']['width'],
$opts['image']['height'],
$opts['loading']
);
return $markup;
}
// customise this function depending on your image CDN and setup
function create_src ( $path, $width, $quality ) {
return CDN_BASE . $path . '?w=' . $width . '&q=' . $quality;
}
function create_srcset( $path, $widths, $quality ) {
$srcset_arr = [];
foreach ($widths as $width) {
$url = create_src( $path, $width, $quality );
$srcset_arr[] = $url . ' ' . $width . 'w';
}
return implode( ',', $srcset_arr );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment