Displaying First Image from ACF Repeater Field

Explore our WordPress category, where you’ll find loads of helpful articles and tutorials for everyone, whether you’re just starting out or a pro developer. Learn about different WordPress themes and plugins that can be applied in various projects according to their specific requirements.
Using Advanced Custom Fields (ACF) in PHP to retrieve a repeater field named ‘photos’ and then displaying the URL of the first image from the repeater.
This code checks if the repeater field ‘photos’ has any rows, iterates through them, and extracts the URL of the first image.
<?php
$count = 0;
$your_repeater = get_field(‘photos’);
if ($your_repeater) {
while (have_rows(‘photos’)) : the_row();
$count++;
$my_field = get_sub_field(‘photos_thumb’);
// Check if $my_field is not empty before assigning to $image1
if ($count == 1 && $my_field) {
$image1 = $my_field;
}
endwhile;
// Check if $image1 is set before echoing its URL
if (isset($image1[‘url’])) {
echo ‘<img src=”‘ . esc_url($image1[‘url’]) . ‘” />’;
} else {
// Handle the case when there is no image
echo ‘No image found’;
}
}
?>
This code checks if the ‘photos_thumb‘ field exists before assigning it to $image1, and it also checks if $image1[‘url’] is set before echoing it to avoid potential PHP errors.