首页 > 解决方案 > Wordpress 类别循环无法检索 ACF 图像给出图像值:NULL

问题描述

我正在尝试从类别中获取图像,但无法检索图像。今天我已经知道我必须使用

get_field('product', $term->taxonomy . '_' . $term->term_id); 获取内容。

但是,当我使用相同的方法从链接到我的自定义帖子类型类别的 ACF 字段中获取图像 URL 时,我没有收到任何值。

这是我的代码(包括 var_dump):

<?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;
?>

我使用这个 var_dump 来查看是否获取了所有内容:

$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>';

唯一的问题是,我没有从我在 ACF 制作的类别中的图像中获得价值。

标签: wordpressforeachwhile-loopcategoriesadvanced-custom-fields

解决方案


您可以通过将术语对象作为第二个参数传递来简单地获取值。

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

在此处查看文档:https ://www.advancedcustomfields.com/resources/adding-fields-taxonomy-term/


推荐阅读