TYPECHO WIKI
每一个作品都值得被记录

Typecho博客实现那年今日代码

Typecho维基君Typecho教程 • 1313次浏览 • 发布 2023-06-17 • 更新 2023-06-17

可以在Typecho博客上展示当前文章日期在过去几年的今天所发的其他文章

之前在一些博客上看到这个那年今日,感觉还不错,就借鉴了一下,并进行优化处理,且兼容了sqlite。

代码

1.将以下代码放入functions.php

function historyToday($created)

{

 $date = date('m/d', $created);

 $date_m = date('m月', $created);

 $date_d = date('d日', $created);

 $time = time();

 $db = Typecho_Db::get();

 $prefix = $db->getPrefix();

 $limit = 5;//显示多少篇文章

  $adapter = $db->getAdapterName();

  if ("Pdo_SQLite" === $adapter || "SQLite" === $adapter) {

 $sql = "SELECT * FROM `{$prefix}contents` WHERE strftime('%m-%d',datetime(datetime(created, 'unixepoch'))) = '{$date}' and created <= {$time} and created != {$created} and type = 'post' and status = 'publish' and (password is NULL or password = '') LIMIT ".$limit;

  }

  if ("Pdo_Mysql" === $adapter || "Mysql" === $adapter || "Mysqli" === $adapter) {

       $sql = "SELECT * FROM `{$prefix}contents` WHERE DATE_FORMAT(FROM_UNIXTIME(created), '%m/%d') = '{$date}' and created <= {$time} and created != {$created} and type = 'post' and status = 'publish' and (password is NULL or password = '') LIMIT ".$limit;

  }

 $result = $db->query($sql);

 $historyTodaylist = [];

 if ($result instanceof Traversable) {

         foreach ($result as $item) {

             $item = Typecho_Widget::widget('Widget_Abstract_Contents')->push($item);

             $title = htmlspecialchars($item['title']);

         $permalink = $item['permalink'];

         $date = date('Y年m月d日',$created);

         $historydate = date('Y年m月d日',$item['created']);

             $historyTodaylist[] = array(

                 "title" => $title,

                 "permalink" => $permalink,

                 "date" => $historydate

             );

 }

 }

if (count($historyTodaylist) > 0){

   echo "<div class='bs-today'>

 <fieldset>

     <legend><h5>那年今日</h5></legend>

     <div class='today-date'><div class='today-m'>{$date_m}</div><div class='today-d'>{$date_d}</div></div><ul>

     ";

     foreach ($historyTodaylist as $item){

         echo "<li><span>{$item['date']}</span><a href='{$item['permalink']}' title='{$item['title']}' target='_blank'>{$item['title']}</a></li>";

     }

     echo "</ul></fieldset></div>";

}

}

2.在文章页面合适的地方插入如下代码:

<?php historyToday($this->created)?>

这样就大功告成了

广告声明:文内含有的对外跳转链接(包括不限于超链接、二维码、口令等形式),用于传递更多信息,节省甄选时间,结果仅供参考,Typecho.Wiki所有文章均包含本声明。
厂商投放

【腾讯云】🎉五一云上盛惠!云服务器99元/月续费同价!

腾讯云五一劳动节海量产品 · 轻松上云!云服务器首年1.8折起,买1年送3个月!超值优惠,性能稳定,让您的云端之旅更加畅享。快来腾讯云选购吧!

广告
添加新评论 »