In ACF, try to never use the_sub_field()
on an image and always have ACF return an image array, especially for larger images. Calling the_sub_field()
directly will bypass WordPress’s image sizing code and should only be used if you have an explicit size that designers are cropping to in Photoshop.
To use a custom size, you need to register it in function.php, usually in after_setup_theme
, via the add_image_size()
function.
add_image_size( 'your-custom-image-size-name', width, height );
For instance:
add_image_size( 'home-featured-service', 900, 900 );
Once you do this you can have WordPress generate your src
, srcset
and sizes
attributes for you:
//Image stored in ACF as an array instead of image $image = get_sub_field( 'image' ); //Get the default image SRC $img_src = wp_get_attachment_image_url( $image[ 'ID' ], 'home-featured-service' ); //Get additional srcsets $img_srcset = wp_get_attachment_image_srcset( $image[ 'ID' ], 'home-featured-service' ); //Get the sizes attribute $img_sizes = wp_get_attachment_image_sizes( $image[ 'ID' ], 'home-featured-service' );
And then write the tag:
<img src="<?php echo esc_url( $img_src ); ?>" srcset="<?php echo esc_attr( $img_srcset ); ?>" sizes="<?php echo esc_attr( $img_sizes ); ?>" alt="" />