wordpress - 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 制作的类别中的图像中获得价值。
解决方案
您可以通过将术语对象作为第二个参数传递来简单地获取值。
$image = get_field('image', $term);
在此处查看文档:https ://www.advancedcustomfields.com/resources/adding-fields-taxonomy-term/
推荐阅读
- javascript - 在数组中查找具有给定字母的单词
- python - pymongo 获取所有集合的键
- r - 用R中的表格列制作堆积条形图
- tensorflow - 用于多类分割的 Dicescore
- c# - WPF ListView 上下文菜单
- amcharts - 使用 amCharts,如何在系列上方添加单个标签?
- c++ - 使用 libcurl 在 smtp 服务器上进行身份验证失败
- elasticsearch - elasticsearch java客户端解析聚合json查询
- api - 如何使用 API 从 PayU 获取所有订单?
- java - 将 AlertDialog 与 AutoCompleteText 结合使用