EP025. “archive.php 归档模板”
🔒 登录后可标记已读点击文章的分类链接(如 /category/awards)或作者链接(如 /author/brad)时,目前是 index.php 兜底顶上去显示,但标题还是写死的「Welcome to our blog!」,不合适。这一讲新建 archive.php,用 the_archive_title() / the_archive_description() 这两个 WordPress 内建函数,自动根据当前是分类归档、作者归档还是日期归档(年/月/日)生成合适的标题和描述文字,不用自己写一堆 is_category() / is_author() 的 if 判断。
涉及文件
wp-content/themes/fictional-university-theme/archive.php(新建,内容基于index.php修改而来)
代码实现
先把 index.php 整份内容复制到新建的 archive.php,然后只改 banner 里的标题和副标题两处:
<?php
get_header(); ?>
<div class="page-banner">
<div class="page-banner__bg-image" style="background-image: url(<?php echo get_theme_file_uri('/images/ocean.jpg') ?>);"></div>
<div class="page-banner__content container container--narrow">
<h1 class="page-banner__title"><?php the_archive_title(); ?></h1>
<div class="page-banner__intro">
<p><?php the_archive_description(); ?></p>
</div>
</div>
</div>
<div class="container container--narrow page-section">
<?php
while(have_posts()) {
the_post(); ?>
<div class="post-item">
<h2 class="headline headline--medium headline--post-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<div class="metabox">
<p>Posted by <?php the_author_posts_link(); ?> on <?php the_time('n.j.y'); ?> in <?php echo get_the_category_list(', '); ?></p>
</div>
<div class="generic-content">
<?php the_excerpt(); ?>
<p><a class="btn btn--blue" href="<?php the_permalink(); ?>">Continue reading »</a></p>
</div>
</div>
<?php }
echo paginate_links();
?>
</div>
<?php get_footer();
?>
其余部分(while 循环、meta box、分页)跟 index.php 完全一样,直接照搬。
[截图:前台访问某个分类归档页(如 /category/awards)时,banner 标题自动显示分类名称的画面]
关于 the_archive_title():transcript 里先演示过手写判断的写法(is_category() 返回 single_cat_title(),is_author() 返回 the_author(),可以自己拼接「Posts by 」之类的前缀文字),但最后决定放弃这条路,改用 the_archive_title() 一个函数就能覆盖分类归档、作者归档、年/月/日归档所有情况,the_archive_description() 同理会自动拉取当前作者的 Biographical Info 或当前分类的 Description。
Hook / Function 速查
| 名称 | 类型 | 用途 |
|---|---|---|
the_archive_title() | WP 内建 function | 自动根据当前归档类型(分类/作者/年/月/日)输出对应标题,无需自己 echo |
the_archive_description() | WP 内建 function | 自动输出当前归档的描述文字(作者的 Biographical Info 或分类的 Description) |
is_category() | WP 内建 function | 判断当前是否为分类归档页(transcript 演示过但最终没采用) |
is_author() | WP 内建 function | 判断当前是否为作者归档页(transcript 演示过但最终没采用) |
single_cat_title() | WP 内建 function | 输出当前分类归档的分类名(transcript 演示过但最终没采用) |
常见坑
the_archive_title()和the_archive_description()都是直接输出型函数(不是get_前缀),不需要也不应该再套一层echo。- 作者归档描述文字为空,是因为后台「用户 → 个人资料 → Biographical Info」没填内容;分类归档描述文字为空,是因为「文章 → 分类 → 编辑该分类 → Description」没填。这两处要各自去后台填才会显示。
延伸 / 后续讲座会用到
博客部分基本完工,下一讲(EP026)开始要把首页那两篇「假」博客卡片换成用自定义查询(WP_Query)拉取的真实最新文章。
Sources
Udemy:
- Become a WordPress Developer: Unlocking Power With Code — Section 6, EP025