WP Custom Post 类型 - 显示分类为 CSS class

WP Custom Post Type - Display taxonomy as CSS class

我在名为 "Portfolio" 的 wordpress 中设置了自定义 post 类型。自定义 post 类型然后设置了两个分类法。它们被命名为 'portfolio_categories' 和 'portfolio_sector'.

目前我正在使用以下代码收集我所有的 'portfolio_categories' 并存储它们,以便它们可以输出为 CSS class 以用于过滤。

<?php while ( $the_query->have_posts() ) : $the_query->the_post(); 
 $termsArray = get_the_terms( $post->ID, "portfolio_categories" );  //Get the terms for this particular item
 $termsString = ""; //initialize the string that will contain the terms
 foreach ( $termsArray as $term ) { // for each term 
 $termsString .= $term->slug.' '; //create a string that has all the slugs 
}
?> 

那么将term输出为classes的代码如下:

<div class="<?php echo $termsString; ?>">
Content goes here
</div>

我需要如何编辑我的代码才能存储分类 'portfolio_sector' 并将它们也输出为 classes?

您还应该在您的上下文中获取其他条款数据

<?php
while ( $the_query->have_posts() ) {
  $the_query->the_post(); 
  $termsArray = get_the_terms( $post->ID, "portfolio_categories" );  //Get the terms for this particular item#
  $termsSectors = get_the_terms( $post->ID, "portfolio_sector" );
  $termsString = ""; //initialize the string that will contain the terms

  foreach ( $termsSectors as $term ) { // for each term 
    $termsSector .= $term->slug.' '; //create a string that has all the slugs 
  }

  foreach ( $termsArray as $term ) { // for each term 
    $termsString .= $term->slug.' '; //create a string that has all the slugs 
  }
}

现在您可以通过 var $termsSector.

回显它

但是,作为提示,您还可以使用 get_the_term_list() 来获取包含 HTML 的列表。也许这对您来说更容易,并且没有必要循环术语数组。