Add srcset and sizes attributes to Advanced Custom Fields image uploads.
<?php
/**
* Use the srcset function in a template file.
*/
<img class="img-class" <?php ccd_responsive_images( get_field( 'img_field' ), 'thumb-640', '640px' ); ?> />
?>
<?php
/**
* Use the srcset with custom image
* sizes in a template file.
*/
$header_img = get_field( 'ccd_header_image' );
$header_size = 'header-large';
$header_src = wp_get_attachment_image_src( $header_img, $header_size );
$header_srcset = wp_get_attachment_image_srcset( $header_img, $header_size );
?>
<img class="header-class" src="<?php echo esc_url( $header_src[0] ); ?>" srcset="<?php echo esc_attr( $header_srcset ); ?>" sizes="(max-width: 640px) 640px, (max-width: 1024px) 1024px, 2048px" />
<?php
/**
* These go in your functions.php file or plugin file.
*/
/*
* Add srcset & sizes.
*/
function ccd_responsive_images( $image_id, $image_size, $max_width ) {
// Check if 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 . '"';
}
}
/*
* Optional: change the WordPress default maximum width of 1600px.
*/
function ccd_max_srcset_image_width() {
return 2048;
}
add_filter( 'max_srcset_image_width', 'ccd_max_srcset_image_width', 10 , 2 );
?>
<?php
/**
* Add srcset & sizes to custom sizes
*
* This goes in your functions.php file or plugin file.
*/
/*
* Add custom image sizes
*
* Example header uses 16:9 HD video aspect ratio
*/
function ccd_add_image_sizes() {
add_image_size( 'header-large', 2048, 1152, true );
add_image_size( 'header-medium', 1024, 576, true );
add_image_size( 'header-small', 640, 360, true );
}
add_action( 'after_setup_theme', 'ccd_add_image_sizes' );
?>
WordPress Snippet
Adds the srcset and sizes attributes to ACF image uploads. Requires installation of the Advanced Custom Fields plugin.
NOTE: ACF image field must be set to return the ID.
NOTE: WordPress needs image sizes with equal aspect ratios in order to generate the srcset, and does not use srcset when images are added as "Full Size".