Skip to content

Instantly share code, notes, and snippets.

@dougkeeling
Created January 10, 2023 18:19
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 dougkeeling/a03c50feaa9116df334deaf7fb4cff16 to your computer and use it in GitHub Desktop.
Save dougkeeling/a03c50feaa9116df334deaf7fb4cff16 to your computer and use it in GitHub Desktop.
[Get markup for a responsive image] In Wordpress, pass an image (attachment) ID to this function to return responsive image markup. If you use Lazysizes, you can return appropriate markup (data-src, data-srcset). #wordpress #PHP #ACF
// Get a responsive image based on an attachment ID
// ------------------------------------------------------------------------------
function rkt_get_responsive_image($image_id, $image_size = 'large', $lazyload = false, $echo = true) {
if ( $image_id ) :
$image_alt = get_post_meta( $image_id, '_wp_attachment_image_alt', true );
$image_args = array(
'srcset' => '',
'alt' => $image_alt,
'width' => '',
'height' => '',
);
if($lazyload) { $image_args['class'] = 'lazyload'; }
$image_markup = wp_get_attachment_image( $image_id, $image_size, false, $image_args );
if($lazyload):
$image_markup = str_replace('src=', 'data-src=', $image_markup);
$image_markup = str_replace('srcset=', 'data-srcset=', $image_markup);
endif;
if($echo):
echo $image_markup;
else:
return $image_markup;
endif;
else:
return false;
endif;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment