Skip to content

Instantly share code, notes, and snippets.

@yratof
Created January 29, 2016 14:45
Show Gist options
  • Save yratof/b67d2a385abcc1ae3ab7 to your computer and use it in GitHub Desktop.
Save yratof/b67d2a385abcc1ae3ab7 to your computer and use it in GitHub Desktop.
Advanced custom fields with Wordpress 4.4 SRCSET
<div class="product__images">
<?php
$image = get_field('billboard_featured_image');
if( !empty( $image ) ) {?>
<img <?php acf_srcset( $image['id'], 'medium', '480px' ); ?> alt="<?php echo $image['alt']; ?>" />
<?php
} else if( has_post_thumbnail() ) {
the_post_thumbnail( 'medium' );
}
?>
</div>
<?php
/**
* Responsive Image Helper Function
*
* @param string $image_id the id of the image (from ACF or similar)
* @param string $image_size the size of the thumbnail image or custom image size
* @param string $max_width the max width this image will be shown to build the sizes attribute
*/
function acf_srcset($image_id,$image_size,$max_width){
// check the image ID is not blank
if($image_id != '') {
// set the default src image size
$image_src = wp_get_attachment_image_url( $image_id, $image_size );
// set the srcset with various image sizes
$image_srcset = wp_get_attachment_image_srcset( $image_id, $image_size );
// generate the markup for the responsive image
echo 'src="'.$image_src.'" srcset="'.$image_srcset.'" sizes="(max-width: '.$max_width.') 100vw, '.$max_width.'"';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment