Skip to content

Instantly share code, notes, and snippets.

@jdhobbsuk
Created October 9, 2019 08:12
Show Gist options
  • Save jdhobbsuk/417ebe471ceae6df9f91629462e3bf1a to your computer and use it in GitHub Desktop.
Save jdhobbsuk/417ebe471ceae6df9f91629462e3bf1a to your computer and use it in GitHub Desktop.
function render_acf_image( $img_obj, $fallback = '900x900', $prefix = '' ) {
if( !empty($img_obj) ):
$img_sizes = $img_obj['sizes'];
$breakpoints = array(
'xs' => '0px',
'sm' => '576px',
'md' => '768px',
'lg' => '992px',
'xl' => '1440px'
);
$sizes = 'sizes="';
$srcset = 'srcset="';
foreach( $breakpoints as $br => $size ):
if( !empty($img_sizes) ):
foreach( $img_sizes as $key => $value ):
$img_url = $prefix.'-'.$br;
$width_arr = $prefix.'-'.$br.'-width';
if( $width_arr == $key ):
$sizes .= '(min-width:'.$size.')';
$sizes .= ' '.$value.'w,';
$srcset .= $img_sizes[$img_url].' '.$value.'w,';
endif;
endforeach;
endif;
endforeach;
$sizes .= '100vw"';
$srcset .= '"';
$img_full = $img_obj['url'];
$img_alt = $img_obj['alt'];
$img_ouput = '<img src="'.$img_full.'" class="img-fluid" alt="'.$img_alt.'" '.$srcset.' '.$sizes.' />';
return $img_ouput;
else:
return '<img src="https://via.placeholder.com/'.$fallback.'" class="img-fluid" alt="" />';
endif;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment