我正在尝试打印出一个类别列表,并使用自定义类将每个类别包装在<span>
中。
当我尝试下面的内容时(参见foreach $ terms作为$ term line),它会打印两次类别,每个范围在类中都有两个类别。
如何运行只能获取其列表类别范围的foreach?
以下当前查询的当前错误样本输出是这样的(用户分析,用户反馈是单独的类别):
<span class="cat user analytics user feedback">user analytics user feedback</span>
<span class="cat user analytics user feedback">user analytics user feedback</span>
PHP
<?php
/*
Query the post
*/
$args = array( 'post_type' => 'company', 'posts_per_page' => -1 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
/*
Pull category for each unique post using the ID
*/
$terms = get_the_terms( $post->ID, 'industry' );
if ( $terms && ! is_wp_error( $terms ) ) :
$links = array();
foreach ( $terms as $term ) {
$links[] = $term->name;
}
$tax_links = join( " ", str_replace(' ', ' ', $links));
$tax = strtolower($tax_links);
else :
$tax = '';
endif;
/* Insert category name into portfolio-item class */
echo '<div class="all portfolio-item '. $tax . '">';
echo '<a href="#" class="company">';
echo'<div class="thmc">';
echo '<div class="thumbnail">';
echo the_post_thumbnail();
echo '</div>';
echo '</div>';
echo '</a>';
echo '<div class="overly">';
echo '<h4 class="company-title">';
echo the_title();
echo '</h4>';
foreach($terms as $term){
echo '<span class="cat ' . $tax . '">';
echo $tax;
echo '</span>';
}
echo '<div class="company-desc">';
echo the_content();
echo '</div>';
echo '<div class="drop-menu-arrow"></div>';
echo '</div>';
echo '</div>';
endwhile; ?>
答案 0 :(得分:0)
演示的简化版本:
$terms = get_the_terms( $post->ID, 'industry' );
foreach( $terms AS $term) {
$class = $term->slug;
echo '<span class="cat ' . $class . '">';
echo $term->name;
echo '</span>';
}
您当然希望在问题的代码中实现一些检查。