现在博客文章的流行将发布时间改成几分钟前或几小时前,那这个效果是怎么实现的?
第一步:在网站所使用主题的 functions.php 文件最后一个?>前中加入以下代码:
//时间格式多久以前 function timeago($ptime) { $ptime = strtotime($ptime); $etime = time() - $ptime; if ($etime < 1) return '刚刚'; $interval = array( 12 * 30 * 24 * 60 * 60 => '年前 (' . date('Y-m-d', $ptime) . ')', 30 * 24 * 60 * 60 => '个月前 (' . date('m-d', $ptime) . ')', 7 * 24 * 60 * 60 => '周前 (' . date('m-d', $ptime) . ')', 24 * 60 * 60 => '天前', 60 * 60 => '小时前', 60 => '分钟前', 1 => '秒前' ); foreach ($interval as $secs => $str) { $d = $etime / $secs; if ($d >= 1) { $r = round($d); return $r . $str; } }; }
第二步:在需要显示时间的地方,把原先显示时间的代码(如:<?php the_time( 'Y年n月j日');?>)改为以下代码即可:
<span title="<?php the_time('Y年n月j日');?>"> <?php echo timeago(get_gmt_from_date(get_the_time('Y-m-d G:i:s'))); ?> </span>
至此,我们已经成功实现将我们的文章发布时间的格式为几分钟前,不过个人建议不要把所有的文章时间格式都改为几分钟前,我们只需要重点修改博客布局的首页(index.php)和分类列表页(category.php)即可。
- 本文固定链接: http://jingyan.idoubi.net/79.html
- 转载请注明: 小雅 于 逗分享开发经验 发表