0
votes

I am trying to get the image from a category but I cannot retrieve the image. Today I already learned that I had to use

get_field('product', $term->taxonomy . '_' . $term->term_id); to fetch content.

But when I use this same method to fetch an image URL from an ACF Field linked to my custom post type category, I do not recieve any values.

This is my code (the var_dump is included):

<?php
$args = array(
'post_type' => 'segments-overview',
'orderby' => 'date', // we will sort posts by date
);

$query = new WP_Query( $args );
$all_terms = [];
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();

$terms = get_the_terms(get_the_ID(), 'category-segments-overview');
foreach($terms as $term) $all_terms[$term->term_id] = $term;

endwhile;

foreach($terms as $term):

?>

<div class="segments-card">
<div class="img">
<?php
$image = get_field('image', $term->taxonomy . '_' . $term->term_id);
if( !empty( $image ) ): ?>
<img src="<?php echo esc_url($image['url']); ?>" alt="<?php echo esc_attr($image['alt']); ?>" />
<?php endif; ?>
</div>
<div class="content">
<div class="title"><?php echo $term->name; ?></div>
<!-- <?php print_r($term); ?> -->
<a class="button transparent" href="/segments/<?php echo $term->slug; ?>">
<?php echo __('View All','axia'); ?>
</a>
</div>
</div>
</div>

<?php endforeach;

wp_reset_postdata();
else :
?>
<div class="no-posts-found">
<h2>There were no items found</h2>
<h3>Please try a different search</h3>
</div>
<?php
endif;
?>

I use this var_dump to see if everything is fetched:

$image = get_field('image', $term->taxonomy . '_' . $term->term_id);
echo '<pre>';

echo "Image field value:";
var_dump($image);

echo "Category field value:";
var_dump($term);

echo '</pre>';

The only thing is that I do not get the value from my image in my category that is made in ACF.

1

1 Answers

0
votes

You can simply get value by passing term object as second parameters.

$image = get_field('image', $term);

Check the docs here: https://www.advancedcustomfields.com/resources/adding-fields-taxonomy-term/