I am trying to output a list of terms associated with a custom taxonomy for each image I am pulling from a custom field, like so:
$portfolio_images = get_field('portfolio_gallery');
Each image has standard WP fields associated with it, such as sizes, title, caption, etc. I would like to output the list of terms associated with each image from the media_category
taxonomy.
I am using get_the_terms
inside another variable but I think something is wrong with my foreach
statement. Any help would be appreciated. Full code:
<?php
$portfolio_images = get_field('portfolio_gallery');
foreach( $portfolio_images as $portfolio_image ):
$labels = get_the_terms( $portfolio_image['ID'], 'media_category' );
?>
<li class="gallery-item" data-myorder="<?php echo $labels; ?>">
<img src="<?php echo $portfolio_image['sizes']['portfolio-thumbnail']; ?>" alt="<?php echo $portfolio_image['alt']; ?>" />
<div class="mask">
<a class="mask-link" href="<?php echo $portfolio_image['url']; ?>">
<div class="mask-content">
<h4><?php echo $portfolio_image['title']; ?></h4>
<p><?php echo $portfolio_image['caption']; ?></p>
</div>
</a>
</div>
</li>
<?php endforeach; ?>
The problem you are facing is that
get_the_terms()
returns anarray
(or false or aWP_Error
-Object), not a string.So, assuming that you have multiple terms for images, you could use a code like this:
This loops through your labels, if no error. You may want to adjust the
$labelstring
to your needs, this one produces a value likelabel1, label2, label3
. You could simply skip the colon, if you don’t need it.Your whole code would look like this: