Typecho 博客归档页面显示每年各发布了多少篇文章
source link: https://hellodk.cn/post/806
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Typecho 博客归档页面显示每年各发布了多少篇文章
上一篇文章提到了如何获取 Typecho 当前用户一共发布了多少篇公开的文章数,文章:Typecho 归档页面显示当前作者/用户的公开文章总数量
今天这篇文章要来获取这个用户每一年发布了多少文章。
搜了一下没有对应的解决方案,更没有 typecho 插件。那么就自己动手吧。应该一个函数就可以搞定的。
登录到后台数据库,发现下面的命令就可以。由于表 typecho_contents
的 created
字段存储的是 unix time stamp(unix 时间戳),我们借助 mysql 原生函数 from_unixtime()
可以转换成普通的年月日-时分秒的形式。
统计 2021 年发布的文章数量
select count(distinct(cid)) from typecho_contents where from_unixtime(created, '%Y')='2021' and status='publish' and type='post';
统计 2020 年发布的文章数量
select count(distinct(cid)) from typecho_contents where from_unixtime(created, '%Y')='2020' and status='publish' and type='post';
统计 2019 年发布的文章数量
select count(distinct(cid)) from typecho_contents where from_unixtime(created, '%Y')='2019' and status='publish' and type='post';
找到了每年发布的公开文章数
下面就是开始写 php 函数了。然而遇到了坑的地方,实际上是我不会 php。
在 typecho 封装的数据库操作工具中,where 子句里可以执行 mysql 原生函数吗,我试了始终不可以(如下代码),希望有知道怎么使用/应用的老哥教教我,在此文下评论一下,谢过了!
->where("from_unixtime('table.contents.created', '%Y') = ?" , $year));
遇到的报错是类似 Database Query Error
,当时没有打开 debug 模式,不过后来想出来后文的解决方案。目前来看实现的还是不错的。
打开 typecho 的 debug 模式,会在异常/错误页面上显示具体问题以及 stack trace 详细信息
/** 开启调试模式,错误页面会显示具体的错误内容 */
define('__TYPECHO_DEBUG__', true);
上述 debug 代码加在博客根目录 config.inc.php
文件中。
下面介绍的两段代码就是最终解决方案。
1. functions.php
在博客主题的 functions.php
中添加如下函数
* 分别获取哪一年发表了多少篇公开文章
function getYearNum($id, $year)
$db = Typecho_Db::get();
date_default_timezone_set('Asia/Shanghai');
$array = $db->fetchAll($db->select('created')
->from('table.contents')
->where('table.contents.authorId = ?', $id)
->where('table.contents.status = ?', 'publish')
->where('table.contents.type = ?', 'post'));
$tempArr = array();
foreach ($array as $item) {
$date = date("Y", (int)($item['created']));
array_push($tempArr, $date);
$resultArr = array_filter($tempArr, function ($ele) use ($year) {
return $ele == $year;
return sizeof($resultArr);
array_filter($tempArr, function ($ele) use ($year) {
这里 use($year)
的用法是在一个群里请教了大佬的,感谢大佬的相助!真是啊。
PHP闭包 function() use()中的详细使用方法
2. page-archives.php
在博客主题对应的 page-archives.php
文件中找到如下代码(可能不完全相同,需要自己确定放置的位置)
if ($year != $year_tmp) {
然后在下面适当位置添加如下代码
$yearNum = getYearNum($this->author->uid, $year);
$output .= '<h4>' . date('Y 年', $archives->created) . '一共发布了 ' . $yearNum . ' 篇文章</h4>';
最终会在每一年的 H3 标题下生成 2020 年一共发布了 50 篇文章
这样的 H4 标题。
最终预览一下我的 归档页面 ,下面是几张截图
如果有帮到你的话,欢迎一键三连!
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK