将每个术语包装在自定义范围/类中


Wrap each term in custom span/class

我正在尝试打印出一个类别列表,并使用自定义类将每个类别包装在<span>中。

当我尝试下面的操作时(请参阅每个$terms作为$term行),它会打印出类别两次,并且每个跨度在类中都有两个类别。

如何运行仅抓取其列表类别跨度的 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; ?>

用于演示的简化版本:

$terms = get_the_terms( $post->ID, 'industry' );  
foreach( $terms AS $term) {
    $class = $term->slug;
    echo '<span class="cat ' . $class . '">';
    echo $term->name;
    echo '</span>';
}

您当然希望实现一些检查,就像您在问题中的代码中所做的那样。