函数代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?php
// 在分类模板文件(如category.php)中使用
if (have_posts()) :
// 获取当前分类页面的分类信息
$current_category = get_queried_object();

while (have_posts()) : the_post();
?>
<article>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>

<!-- 显示当前分类页面所属分类 -->
<div class="post-category">
分类:
<a href="<?php echo esc_url(get_category_link($current_category->term_id)); ?>">
<?php echo esc_html($current_category->name); ?>
</a>
</div>

<!-- 添加文章标签显示 -->
<div class="post-tags">
<?php
$tags = get_the_tags();
if ($tags) :
echo '标签: ';
foreach ($tags as $tag) {
echo '<a href="' . esc_url(get_tag_link($tag->term_id)) . '">' . esc_html($tag->name) . '</a> ';
}
endif;
?>
</div>
</article>
<?php
endwhile;

// 分页导航
the_posts_pagination();

// 重置主循环
wp_reset_postdata();
else :
echo '没有找到文章';
endif;
?>

关键函数说明:

1.get_queried_object()

获取当前分类页面的分类对象(包含term_id、name等信息)

2.get_the_category()

获取当前文章的所有分类信息数组

通过分类ID获取分类归档页链接

4.wp_reset_postdata()

重置循环数据(使用自定义查询时必须调用)