Get values from a media attachment

Overview

All the template functions (get_field, the_field, etc) can be used to load values from a media attachment, however, a second parameter is required to target the attachment.

Each post has a unique ID which can be found in the URL when editing, or found via code such as $attachment->ID.

The reason as to why this is the same as targeting a post object is because WP saves all media attachments as post objects in the wp_posts table.

Examples

Display a field

<p><?php the_field('field_name', 12); ?></p>

Retrieve a field

<?php

$variable = get_field('field_name', 13);

// do something with $variable

?>

Retrieve from another image custom field

This example will show how to load a selected image from a custom field, and then load a custom field from that image.

<?php 

// get an image field
$image = get_field('image');

// each image contains a custom field called 'link'
$link = get_field('link', $image['ID']);

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

Working with the Repeater Field

Note that when inside of a have_rows loop, you do not need to use the $post_id parameter for any sub field functions (get_sub_field, the_sub_field)

<?php if( have_rows('repeater', 123) ): ?>

    <ul>

    <?php while( have_rows('repeater', 123) ): the_row(); ?>

        <li><?php the_sub_field('title'); ?></li>

    <?php endwhile; ?>

    </ul>

<?php endif; ?>

Related

Hi all. Server maintenance scheduled this Sunday 28th May. Learn more