我正在寻找一种更好的方法来输出循环中帖子的类别列表。这是我的文件:
<?php $category = get_the_category(); ?>
<a href="<?php echo get_category_link($category[0]->cat_ID); ?>"><?php echo $category[0]->cat_name; ?></a>,
<a href="<?php echo get_category_link($category[0]->cat_ID); ?>"><?php echo $category[1]->cat_name;?></a>,
<a href="<?php echo get_category_link($category[0]->cat_ID); ?>"><?php echo $category[2]->cat_name;?></a>
显然这不是很好,因为如果没有三个类别,我会得到多余的逗号。用逗号循环遍历和输出类别的最佳方法是什么?
Thanks very much
这段代码应该可以工作了:
<?php
$separator = ',';
$output = '';
$categories = get_the_category();
if ($categories){
foreach($categories as $category) {
$output .= '<a href="'.get_category_link( $category->term_id ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '">'.$category->cat_name.'</a>'.$separator;
}
echo trim($output, $separator);
}
?>
关于wordpress codex中get_the_category()
函数的更多信息和示例
可以使用
<?php echo get_the_category_list(); ?>
将以这种格式输出所有内容(作为列表):
<ul class="post-categories">
<li>
<a href="http:myblog.com/category/business" title="View all posts in Business" rel="category tag">Business</a>
</li>
</ul>
你可以在这里阅读更多信息
或者如果你使用
<?php wp_get_post_categories( $post_id, $args ); ?>
它将以数组形式输出类别id
所以像
$post_categories = wp_get_post_categories( $post->ID );
foreach($post_categories as $c){
$cat = get_category( $c );
$link = get_category_link( $c );
echo "<a href='{$link}'>{$cat->name}</a>";
}
可能更适合你
你可以在这里阅读更多关于这个函数的信息