Skip to content

Instantly share code, notes, and snippets.

@nikola0203
Last active March 2, 2022 11:35
Show Gist options
  • Save nikola0203/37fe41d852deb0dee22e4bf642f600dc to your computer and use it in GitHub Desktop.
Save nikola0203/37fe41d852deb0dee22e4bf642f600dc to your computer and use it in GitHub Desktop.
ACF image with lazy load classes
/**
* ACF image
*
* @param array $image_array
* @param string $size
* @param string $css_class
* @return html
*/
public static function acfImage( $image_array, $size = 'thumbnail', $css_class = '' )
{
if ( !empty( $image_array ) ) {
$fullWidth = $image_array['width'];
$fullWidthSrc = $image_array['url'];
if ( 'full' != $size ) {
$src = $image_array['sizes'][$size];
$width = $image_array['sizes'][$size . '-width'];
$height = $image_array['sizes'][$size . '-height'];
} else {
$src = $fullWidthSrc;
$width = $fullWidth;
$height = $image_array['height'];
}
$image_attributes = '
width = "' . esc_attr( $width ) . '"
height = "' . esc_attr( $height ) . '"
src = "' . esc_url( $src ) . '"
class = "lazyload lazy-fade '. $css_class .'"
alt = "' . esc_attr( $image_array['alt'] ) . '"
loading = "lazy"
';
if ( 'thumbnail' != $size ) {
switch ( $size ) {
case 'medium':
$srcset = '
' . esc_url( $src ) . ' ' . esc_attr( $width ) . 'w,
' . esc_url( $image_array['sizes']['medium_large'] ) . ' 768w,
' . esc_url( $image_array['sizes']['large'] ) . ' 1024w,
' . esc_url( $fullWidthSrc ) . ' ' . $fullWidth . 'w
';
break;
case 'medium_large':
$srcset = '
' . esc_url( $src ) . ' ' . esc_attr( $width ) . 'w,
' . esc_url( $image_array['sizes']['medium'] ) . ' 300w,
' . esc_url( $image_array['sizes']['large'] ) . ' 1024w,
' . esc_url( $fullWidthSrc ) . ' ' . $fullWidth . 'w
';
break;
case 'large':
$srcset = '
' . esc_url( $src ) . ' ' . esc_attr( $width ) . 'w,
' . esc_url( $image_array['sizes']['medium'] ) . ' 300w,
' . esc_url( $image_array['sizes']['medium_large'] ) . ' 768w,
' . esc_url( $fullWidthSrc ) . ' ' . $fullWidth . 'w
';
break;
case 'full':
$srcset = '
' . esc_url( $src ) . ' ' . esc_attr( $width ) . 'w,
' . esc_url( $image_array['sizes']['medium'] ) . ' 300w,
' . esc_url( $image_array['sizes']['medium_large'] ) . ' 768w,
' . esc_url( $image_array['sizes']['large'] ) . ' 1024w
';
break;
}
$image_attributes .= 'srcset="'. $srcset .'"';
$image_attributes .= 'sizes="(max-width: ' . esc_attr( $width ) . 'px) 100vw, ' . esc_attr( $width ) . 'px"';
}
$image_html = '<img ' . $image_attributes . ' >';
echo wp_kses_post( $image_html );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment