Get an ACF Image Field with All Sizes

Retrieve image field data and output specific image sizes with proper alt text and responsive srcset.

php field-types
|

Retrieve image field data and output specific image sizes with proper alt text and responsive srcset.

Set the image field’s return format to Image Array in the field settings, then use the returned data:

<?php
$image = get_field( 'hero_image' );

if ( $image ) : ?>
    <img
        src="<?php echo esc_url( $image['url'] ); ?>"
        alt="<?php echo esc_attr( $image['alt'] ); ?>"
        width="<?php echo esc_attr( $image['width'] ); ?>"
        height="<?php echo esc_attr( $image['height'] ); ?>"
    />
<?php endif; ?>

To output a specific size (e.g. medium, large, or a custom size):

<?php
$image = get_field( 'hero_image' );

if ( $image ) : ?>
    <img
        src="<?php echo esc_url( $image['sizes']['large'] ); ?>"
        alt="<?php echo esc_attr( $image['alt'] ); ?>"
        width="<?php echo esc_attr( $image['sizes']['large-width'] ); ?>"
        height="<?php echo esc_attr( $image['sizes']['large-height'] ); ?>"
    />
<?php endif; ?>

For the best approach — responsive images with automatic srcset — use wp_get_attachment_image() with the image ID return format:

<?php
$image_id = get_field( 'hero_image' );

if ( $image_id ) {
    echo wp_get_attachment_image( $image_id, 'large', false, [
        'class'   => 'hero-image',
        'loading' => 'lazy',
    ] );
}

Related Snippets

Stay Updated

Get ACF tips and new extensions in your inbox

No spam. Unsubscribe anytime.