在wordpress中只显示一个类别

时间:2015-11-13 20:25:59

标签: php wordpress

我有一个分配到不同类别的帖子。 我创建了一个循环

<div class="col-sm-12 ">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<section class="row marginbottomclass">

<div class="col-sm-4 thumbnailimage">
<a href="<?php the_permalink(); ?>"> <?php the_post_thumbnail(); ?> </a>
</div>

<div class="col-sm-8">
<h1><?php the_title( ); ?></h1>
<small><?php the_category("," );?></small>
<p><?php the_excerpt(); ?></p>

</div>


</section>
<div class="clearfix"></div>
<?php endwhile; else : ?>

<?php endif; ?>
</div>

但是这个循环得到了所有类别的帖子。虽然我只想展示一个类别。我不想显示此帖子分配给的所有类别。

我尝试了不同的

<?php $parentscategory ="";
foreach((get_the_category()) as $category) {
if ($category->category_parent == 0) {
$parentscategory .= ' <a href="' . get_category_link($category->cat_ID) . 
 '" title="' . $category->name . '">' . $category->name . '</a>, ';
}
}
echo substr($parentscategory,0,-2); ?>

1 个答案:

答案 0 :(得分:0)

我认为您可能想要使用wp_get_post_terms,这会获取附加到帖子的所有类别并将它们放入数组中。

<?php
$term_list = wp_get_post_terms($post->ID, 'my_taxonomy', array("fields" => "all"));
echo $term_list[0]->description ;
?>