在$query循环遍历自定义分类法时,Funders分类出现数据累加问题
问题
在WordPress页面的「Current Research Focus」区块中,每个区块需要展示关联的Researchers、Partners和Funders(三者均为自定义分类法)。其中Researchers和Partners显示正常,但Funders会累加所有区块的结果——到最后一个区块时,会包含前面所有区块的资助者名称。三者循环逻辑看似一致,求问题原因。
页面相关代码
while ($query->have_posts()) { $query->the_post(); global $post; $topic = wp_get_object_terms( $post->ID, 'topic', array('taxonomy' => 'topic') ); ?> <div class="current-research-container"> <div class="current-research-body"> <div class="current-research-header"> <h5 class="current-research-focus">current research focus</h5> <div class="current-research-topics-container"> <?php foreach($topic as $topics) { $color = get_field('topic-color', 'topic' . '_' . $topics->term_id); echo '<a class="current-research-button" style="border-color:' . $color . ';"href="' . get_category_link($topics->term_id) . '">' . $topics->name . '</a>'; } ?> </div> </div> <h4><?php the_title(); ?></h4> <p class="current-research-bio"><?php echo get_field('research_text'); ?></p> <?php $terms_author = get_the_terms( $post->ID, 'authors' ); if ($terms_author) { $terms_author_str = array(); echo '<p class="taxonomy-data"><strong>Researchers </strong>'; foreach($terms_author as $term_author) { $terms_author_str[] = $term_author->name; } echo implode(", ",$terms_author_str); } $terms_partner = get_the_terms( $post->ID, 'partners' ); if ($terms_partner) { $terms_partner_str = array(); echo '<p class="taxonomy-data"><strong>Partners </strong>'; foreach($terms_partner as $term_partner) { $terms_partner_str[] = $term_partner->name; } echo implode(", ",$terms_partner_str); } $terms_funder = get_the_terms( $post->ID, 'funders' ); if ($terms_funder) { echo '<p class="taxonomy-data"><strong>Funders </strong>'; foreach($terms_funder as $term_funder) { $terms_funder_str[] = $term_funder->name; } echo implode(", ",$terms_funder_str); } ?> </div> <?php $image = get_field('current-research-image'); if( !empty( $image ) ): ?> <div class="current-research-inner-right current-research-image-container"> <div class="img-ratio-box img-treatment"> <div class="img-ratio-box-inside"> <img class="" src="<?php echo esc_url($image['url']); ?>"> </div> </div> </div> <?php endif; ?> </div> <?php }
问题原因与修复方案
原因
$terms_funder_str数组没有在每个区块的循环中初始化。PHP中,数组变量如果不重新声明为空数组,会保留上一次循环的内容。每次遍历新的Research区块时,都会往同一个$terms_funder_str数组里追加当前区块的资助者,最终导致后面的区块包含前面所有区块的结果。而Researchers和Partners对应的$terms_author_str、$terms_partner_str都在各自的if判断内做了$xxx_str = array();的初始化,所以不会出现累加问题。
修复代码
只需在Funders的if判断内,先初始化$terms_funder_str为空数组:
$terms_funder = get_the_terms( $post->ID, 'funders' ); if ($terms_funder) { $terms_funder_str = array(); // 新增这行初始化代码 echo '<p class="taxonomy-data"><strong>Funders </strong>'; foreach($terms_funder as $term_funder) { $terms_funder_str[] = $term_funder->name; } echo implode(", ",$terms_funder_str); }
内容的提问来源于stack exchange,提问作者samseurynck
相关产品推荐
相关产品推荐

