typecho首页输出指定时段的文章
嘿嘿!最近一直在对主题断断续续的优化、精简掉一些无用的功能,然后翻看以前的动态时感觉这些陈年旧事没必要全都在首页输出吧,于是想着首页能不能像微信朋友圈那样非好友只能看近 10 天的动态 。
但博客没有好友不好友的说法呀,原本想通过cookie来当做是否好友的,但我并没有开启评论功能呀,那仿一个样子就行了吧,于是费了好大劲终于弄出来,代码经反复推敲已优化至最精简。至少不明所以的人还以为是真的呢😎,如下图:
✨ 改造方法
- 把下列代码丢进
functions.php的themeInit函数内
//首页输出近一年的文章
if ($archive->is('index')) {
$oneYearAgo = strtotime('-1 year');
try {
$db = Typecho_Db::get();
$count = $db->fetchObject($db->select(array('COUNT(*)' => 'num'))
->from('table.contents')
->where('table.contents.created >= ?', $oneYearAgo)
->where('table.contents.type = ?', 'post')
->where('table.contents.status = ?', 'publish'))->num;
$archive->setTotal($count);
} catch (Exception $e) {
error_log("Filter recent posts error: " . $e->getMessage());
}
}- 同时在首页
index.php循环外加入下列代码
<?php
$archive = $this->_archive;
if ($archive->is('index')):
$currentPage = $this->_currentPage;
$totalPages = ceil($this->getTotal() / $this->parameter->pageSize);
if($currentPage >= $totalPages): ?>
<a class="well">—— 非王较瘦的朋友只显示最近一年的动态 ——</a>
<?php endif; ?>
<?php endif; ?>ok,一个酷似朋友圈的小功能大功告成,陈年旧事自已都没耐心一页一页的翻看😓。发挥想象,还可继续拓展,比如增加后台设置……
