功能介绍:利用时间做一个列表,比如2024年3月(链接为:https://域名/2024-02)显示2024年2月份的所有文章,2024年3月(链接为:https://域名/2024-03)显示2024年3月份的所有文章…依此类推!
1、新增一个archive-custom.php模板,参考代码如下:
<?php
// 从URL中获取年份和月份
$year_month = get_query_var('name');
if ($year_month) {
list($year, $month) = explode('-', $year_month);
}
// 确保$year和$month是数字,并且$month在1到12之间
if (is_numeric($year) && is_numeric($month) && $month >= 1 && $month <= 12) {
// 创建WP_Query来查询文章
$args = array(
'year' => $year,
'monthnum' => $month,
'posts_per_page' => -1, // 显示所有文章
);
$query = new WP_Query($args);
// 检查是否有文章
if ($query->have_posts()) {
// 开始文章循环
while ($query->have_posts()) {
$query->the_post();
echo '<dl><dt>' . the_post_thumbnail() . '</dt>';
// 显示文章标题和链接
echo '<dd class="title"><a href="' . get_the_permalink() . '">' . get_the_title() . '</a></dd>';
// 显示文章内容摘要
echo '<dd class="desc">' . get_the_excerpt() . '</dd>';
// 显示标签
$tags = get_the_tags();
if ($tags) {
$tag_links = array();
foreach ($tags as $tag) {
$tag_link = get_tag_link($tag->term_id);
$tag_links[] = '<a href="' . $tag_link . '">' . $tag->name . '</a>';
}
echo '<dd class="tags">' . implode('', $tag_links) . '</dd></dl>';
}
// 显示文章内容(可选)
//the_content();
// 其他文章信息,比如发布日期、特色图片等(可选)
// the_date();
// the_post_thumbnail();
// 可以在这里添加更多自定义的HTML和模板标签
}
// 分页导航(如果设置了分页的话)
//the_posts_navigation();
} else {
// 如果没有文章,显示消息
echo '没有找到该月份的文章。';
}
// 恢复原始的文章数据
wp_reset_postdata();
} else {
// URL不匹配,显示错误消息
echo '无效的URL。';
}
?>
2、找到主题文件夹中的functions.php文件中,添加以下代码:
function custom_archive_rewrite_rules() {
add_rewrite_rule(
'^([0-9]{4})-([0-9]{1,2})/?$',
'index.php?name=$matches[1]-$matches[2]',
'top'
);
}
add_action('init', 'custom_archive_rewrite_rules');
function custom_archive_query_vars($query_vars) {
$query_vars[] = 'name';
return $query_vars;
}
add_filter('query_vars', 'custom_archive_query_vars');
3、打开wordpress后台管理页面,左边菜单选择“页面”→“新增页面”,标题改成2024/02,页面链接自动生成成2024-02,页面模板选择archive-custom新增就可以了!