this is a follow up to this question advanced custom fields can't do nested loops repeater inside repeater have_rows() not doing anything
Now I’m stuck on a problem where I can’t get the sub field URL.
<div class="tc__agenda-speaker">
<?php while (have_rows('agenda_event_speakers')) : the_row(); ?>
<div class="tc__agenda-speaker-headshot">
<!-- DEBUG LINE -->
<div style="color: red;"><?php echo the_sub_field('agenda_event_speaker_headshot')['src'] ?></div>
<img src="<?php the_sub_field('agenda_event_speaker_headshot')['url'] ?>" alt="<?php the_sub_field('agenda_event_speaker_headshot')['alt'] ?>">
</div>
<div class="tc__agenda-speaker-info">
<h4><?php the_sub_field('agenda_event_speaker_name') ?></h4>
<p><?php the_sub_field('agenda_event_speaker_title') ?></p>
</div>
<?php endwhile ?>
</div>
<?php endif ?>
This line
<?php the_sub_field('agenda_event_speaker_headshot')['url'] ?>
It’s output is this
16835, 16835, Name color 2, Name-color-2.png, 152744, http://website.com/wp-content/uploads/2021/02/Name-color-2.png, http://website.com/post/post-title-here/Name-color-2/, , 86, , , Name-color-2, inherit, 16799, 2021-02-02 16:45:53, 2021-02-02 16:45:53, 0, image/png, image, png, http://website.com/wp-includes/images/media/default.png, 500, 500, Array
The fields returns format is array
Advanced Custom Fields get sub field image
You can use get URL of Image by get_sub_field(‘imgcolumn_1’)[‘url’];
As function get_sub_field() returns an array.
this documentation https://www.advancedcustomfields.com/resources/the_sub_field/ indicates there’s no difference in accessing indexes
It does say
This function is essentially the same as echo get_sub_field()
If I go
<?php echo the_sub_field('agenda_event_speaker_headshot')['url'] ?>
the img src is unknown
How do you access url index of image array in a sub field in advanced custom fields?
2
Answers
Very simple - i had no image set in the field in the first place...
This is in fact the correct code.
"Essentially the same" and "The same" is where you’re getting tripped up. One of the places where
the_sub_field()
andget_sub_field()
are different is when you are dealing with values that cannot be directly converted to a string.To answer your immediate question; you need to do exactly what you talk about in the question, namely change:
To
The reason for this is that
the_sub_field()
does not return a value itecho
es the value so there is no array with a propertyurl
for you to access. What your original code is doing is essentially the same asWhich isn’t what you want.
The reason that you’re getting
unknown
is thatthe_sub_field()
does attempt to output something; but because this particular subfield is more complex it doesn’t work how you expect. Inside that function something like this is happening:I expect that if one were to look under the hood of
the_sub_field()
you would see something essentially like this: