0

I have a question about nested acf fields. I can't figure out a great way to use have_rows() when a repeater/flexible content is nested within another field.

Normally, I would access the data like this:

if (have_rows('field_with_many_rows')) : 
  while (have_rows('field_with_many_rows') : the_row();
    $title = get_sub_field('title');
    $copy  = get_sub_field('copy');
    ?> 
      <h1><?php echo $title ?></h1>
      <p><?php echo $copy ?></p>
    <?php
  endwhile;
endif;

But that doesn't seem to work when the flexible content field is nested within another field.

What's the nicest way to access nested data with have_rows()? I like using it, because it's the neatest way to iterate over a field with multiple entries - but open to better strategies..

1 Answer 1

1

ACF official documentation indicates it should be as simple as using have_rows() again:

if ( have_rows( 'field_1' ) ) {
    while ( have_rows( 'field_1 ' ) ) {
        the_row();

        if ( have_rows( 'field_2' ) ) {
            while ( have_rows( 'field_2' ) ) {
                the_row();

                $value = get_sub_field( ... );
            }
        }
    }
}

Note that if the parent field is a group field, have_rows() will treat it as if it has one row, and you will have to declare the other fields outside the have_rows() loop. This answer is a good reference.

4
  • what if field_1 is a group field? Jun 20, 2023 at 20:03
  • AFAIK, have_rows() will work with a group field. Seems like it: stackoverflow.com/questions/52057378/…
    – Caleb
    Jun 20, 2023 at 20:07
  • This might be a dumb question, but how do you access data when using have_rows() with a group? I'm not sure what variables are available to me .. Jun 20, 2023 at 20:55
  • I added a note about what to do when the parent field is a group (because that was my main concern when asking the question). Feel free to edit! Jun 20, 2023 at 21:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.