get_the_category
也可以在循环中工作,不传递帖子ID,它将默认为循环中的当前帖子。
The first example in the docs for get_the_category
显示如何输出第一个(或唯一)类别的url和名称:
$categories = get_the_category();
if ( ! empty( $categories ) ) {
echo \'<a href="\' . esc_url( get_category_link( $categories[0]->term_id ) ) . \'">\' . esc_html( $categories[0]->name ) . \'</a>\';
}
编辑:添加了上述示例的原始代码:
<div class="container body-margin">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div class="card">
<div class="row">
<?php $url = wp_get_attachment_url( get_post_thumbnail_id(get_the_ID()), \'thumbnail\' ); ?>
<img src="<?php echo $url ?>" class="img-responsive card-image" />
</div>
<div class="row card-body">
<?php
$categories = get_the_category();
if ( ! empty( $categories ) ) {
echo \'<div><a class="card-body-category" href="\' . esc_url( get_category_link( $categories[0]->term_id ) ) . \'">\' . esc_html( $categories[0]->name ) . \'</a></div>\';
}
?>
<div><h4 class="card-body-title"><b><?php the_title(); ?></b></h4></div>
<div><p class="card-body-date"><?php the_date(); ?></p></div>
</div>
</div>
<?php endwhile; ?>
</div>