ACF分类颜色字段在关联项目文章中显示异常,求代码修正
解决ACF分类颜色字段在文章中重复显示的问题
你遇到的核心问题是在文章循环里错误获取了所有分类,而非当前文章关联的专属分类,导致所有文章都复用了同一个分类的颜色值。下面是修正后的代码和关键说明:
修正后的文章数组代码
<?php $args = array( 'post_type' => 'project', 'posts_per_page' => -1, ); $posts_array = get_posts($args); $array = []; // 提前初始化数组避免PHP警告 foreach($posts_array as $post){ $post = (array)$post; $location = get_field('google_map', $post['ID']); // 获取当前文章关联的project-cat分类(替换原有的get_terms) $related_terms = get_the_terms($post['ID'], 'project-cat'); $catColor = ''; $catID = ''; // 处理分类获取失败或无关联分类的情况 if (!empty($related_terms) && !is_wp_error($related_terms)) { // 取第一个关联分类的颜色(若文章关联多个分类,可按需调整逻辑) $target_term = $related_terms[0]; $catColor = get_field('marker', $target_term->taxonomy . '_' . $target_term->term_id); $catID = $target_term->term_id; // 如果你想沿用原代码的taxo字段,也可以保留:$catID = get_field('taxo',$post['ID']); } $array[] = array( 'title' => $post['post_title'], 'subtitle' => get_field('status', $post['ID']), 'catColor' => $catColor, 'catID' => $catID, 'lat' => $location['lat'], 'lng' => $location['lng'], 'url' => get_permalink($post['ID']), ); } ?>
关键改动说明
- 精准获取关联分类:用
get_the_terms($post['ID'], 'project-cat')替代get_terms('project-cat'),这样只会拿到当前文章绑定的分类,而非全部分类集合。 - 增加容错处理:加入
!empty($related_terms) && !is_wp_error($related_terms)判断,避免文章无关联分类时出现报错。 - 灵活调整分类逻辑:默认取第一个关联分类的颜色,如果你的业务允许文章绑定多个分类,可以在这里添加循环或自定义规则,选择需要展示的分类颜色。
额外优化方案
如果你的taxo字段是专门存储文章关联分类ID的,也可以直接用这个值获取颜色,代码更简洁:
$catID = get_field('taxo', $post['ID']); $catColor = $catID ? get_field('marker', 'project-cat_' . $catID) : '';
内容的提问来源于stack exchange,提问作者atousa najafi
相关产品推荐
相关产品推荐

