Created
January 10, 2023 18:19
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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