I’m working with Advanced Custom Fields (ACF) in WordPress, and I’m having trouble correctly looping through a complex repeater and group field structure to display the data on my site.
Here is the structure of my ACF fields:
- “locations” (Repeater field)
-
“country” (Group field)
-
“country_name” (Text field)
-
“country_locations” (Repeater field)
-
“city” (Group field)
-
“city_name” (Text field)
-
“city_company_name” (Text field)
-
“city_image” (Image field)
-
-
-
-
I want to display the data on the front end in a layout like this:
<div>
<h2>country_name1</h2>
<div>
<h4>city_name1</h4>
<h5>city_company_name1</h5>
<img city_image1/>
</div>
<div>
<h4>city_name2</h4>
<h5>city_company_name2</h5>
<img city_image2/>
</div>
</div>
I have tried various ways to loop through each Repeater fields, but with no luck, I only got the Country names.
<?php if (have_rows('locations')) : ?>
<?php while (have_rows('locations')) : the_row(); ?>
<?php $country = get_sub_field('country'); ?>
<div>
<h2>Country Name: <?php echo $country['country_name']; ?></h2>
<?php if (have_rows('country_locations', 'country')) : ?>
<?php while (have_rows('country_locations', 'country')) : the_row(); ?>
<?php $city = get_sub_field('city'); ?>
<div>
<h4>City: <?php echo $city['city_name']; ?></h4>
<h5>Company: <?php echo $city['city_company_name']; ?></h5>
<?php if ($city['city_image']) : ?>
<div>
<img src="<?php echo $city['city_image']['url']; ?>" alt="<?php echo $city['city_image']['alt']; ?>" />
</div>
<?php endif; ?>
</div>
<?php endwhile; ?>
<?php endif; ?>
</div>
<?php endwhile; ?>
<?php endif; ?>