Support

Account

Home Forums General Issues Looping over sub fields in different ways

Solved

Looping over sub fields in different ways

  • Hi!

    I have accustomed myself to do this when looping over sub fields:

    
    $links = get_field( 'footer', settings_id() )['legal_links'];
    if ( !empty( $links ) ) {
      foreach ( $links as $link ) {
        if ( !empty( $link ) {
          var_dump( $link );
        }
      }
    }
    

    In my opinion it’s really straightforward and just works.

    Can this have some negative repercussions as opposed to have_rows() and a while loop like everywhere in the docs?

    Thanks

  • That looks like it’s for a group field. This will also work for sub fields of a group field

    
    $links = get_field('footer_legal_links', settings_id());
    

    I personally find this easier to look at but they have the same meaning. But I always try to comment code when using a group field that it is a group field.

    The only time you’re going to need to use have_rows() is if you have a repeater as a sub field of a group field so that you can loop over the repeater. Without the parent have_rows() on the group field you would have to get the repeater as an array an loop over the content of the array.

  • Thanks John, that makes things clear.

    Also good to know I can do it the way you’re mentioning, although I personally find the appending of sub fields a better way to do it:)

  • For me it wouldn’t matter what way I do it becuase I always make sure I comment group fields and why I am getting the fields in a specific way because of the fact that you can access sub fields of a group in multiple ways. I’ve discovered that it helps when I look back at my older code.

  • That makes sense, although I’m the lazy kind and can’t rely on myself commenting it all. Standardization is a better fit for me:)

Viewing 5 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic.