Advanced Custom Fields (ACF): Image field template usage

Last updated on

The ACF custom image field in WordPress will return either an Image Object (array), a URL (string) or an Image ID (int) depending on the Return Value you set in your custom field.

Image Object (Basic Usage)

This example shows how to display the selected image when using the object return type. This return type allows us to easily access extra image data such as alt.

<?php

$image = get_field('my_custom_image_field');

if( !empty($image) ): ?>

	<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />

<?php endif; ?>

Image Object (Advanced Usage)

This example shows how to display a custom size of the selected image when using the object return type. This return type allows us to easily access extra image data such as sizes, width, height and more.

<?php 

$image = get_field('my_custom_image_field');

if( !empty($image) ): 

	// vars
	$url = $image['url'];
	$title = $image['title'];
	$alt = $image['alt'];
	$caption = $image['caption'];

	// thumbnail
	$size = 'thumbnail';
	$thumb = $image['sizes'][ $size ];
	$width = $image['sizes'][ $size . '-width' ];
	$height = $image['sizes'][ $size . '-height' ];

	if( $caption ): ?>

		<div class="wp-caption">

	<?php endif; ?>

	<a href="<?php echo $url; ?>" title="<?php echo $title; ?>">

		<img src="<?php echo $thumb; ?>" alt="<?php echo $alt; ?>" width="<?php echo $width; ?>" height="<?php echo $height; ?>" />

	</a>

	<?php if( $caption ): ?>

			<p class="wp-caption-text"><?php echo $caption; ?></p>

		</div>

	<?php endif; ?>

<?php endif; ?>

Image URL

This example shows how to display the selected image when using the URL return type. This return type allows us to efficiently display a basic image but prevents us from loading any extra data about the image.

<?php if( get_field('my_custom_image_field') ): ?>

	<img src="<?php the_field('image'); ?>" />

<?php endif; ?>

Image ID

This example shows how to display the selected image when using the ID return type. This return type allows us to efficiently load only the necessary image data.

<?php 

$image = get_field('my_custom_image_field');
$size = 'full'; // (thumbnail, medium, large, full or custom size)

if( $image ) {

	echo wp_get_attachment_image( $image, $size );

}

?>

Let me know if this helped. Follow me on Twitter, Facebook and YouTube, or 🍊 buy me a smoothie.

Leave a reply

Your email address will not be published. Required fields are marked *