update 下文代码已经修改,可以实现人性化显示日志和回复的发表时间
通常的日志发表时间都显示为年月日的形式,这个方法是把它改成显示为几小时前、几天前或者几年前的形式,如我测试的时候是显示为This entry was posted 9 months ago,然后将回复的时间改成日志发表后多长时间回复的形式。代码是一个老外的博客上看到的,我测试了可以用,不过我是想时间超过24小时就显示为正常的年月日,可是本人不懂php,不知道怎么修改,只好放弃不用,发出来给感兴趣的人用了。
在主题文件夹下的function.php文件里最底部的 ?>前加入以下代码:
<?php
function time_since($older_date, $newer_date = false)
{
$chunks = array(
//因为在24小时以外的我需要显示正常时间,所以这里用不到/年/月/周/天,需要的同学可以去掉以下注释符
//array(60 * 60 * 24 * 365 , '年'),
//array(60 * 60 * 24 * 30 , '月'),
//array(60 * 60 * 24 * 7, '周'),
//array(60 * 60 * 24 , '天'),
array(60 * 60 , '小时'),
array(60 , '分钟'),
);
$newer_date = ($newer_date == false) ? (time()+(60*60*get_settings("gmt_offset"))) : $newer_date;
$since = $newer_date - $older_date;
//当前时间与发布时间差,这里我取86400秒,即24小时
if($since < 86400)
{
//显示时间的前半部分
for ($i = 0, $j = count($chunks); $i < $j; $i++)
{
$seconds = $chunks[$i][0];
$name = $chunks[$i][1];
if (($count = floor($since / $seconds)) != 0)
{
break;
}
}
$output = "$count {$name}";
//显示时间的后半部分
if ($i + 1 < $j)
{
$seconds2 = $chunks[$i + 1][0];
$name2 = $chunks[$i + 1][1];
if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0)
{
$output .= ", $count2 {$name2}";
}
}
return $output." 前";
//在24小时以外的时间显示格式
}else{
the_time('Y-m-j G:i');
}
}
?>
然后在你需要显示时间的地方用下面的代码替换,日志部分:
<?php if (function_exists('time_since')) {
echo time_since(abs(strtotime($post->post_date_gmt . "GMT")), time()) . " ago";
} else {
the_time('F jS, Y');
} ?>
判断语句是为了防止function.php文件里没加入那代码时无法显示,如果确认有加,可以去掉这个判断,看起来会更简洁点。
然后在comments.php里将回复的时间的地方替换成下面的代码,(这个可能有点麻烦,现在主题很少comments.php文件独立写了,都是调用wp默认的,只有单独写代码的才有的改):
<?php if (function_exists(‘time_since’)) {
echo time_since(abs(strtotime($comment->comment_date_gmt . “ GMT”)), time()) . “ ago”;
} else {
the_time(‘F jS, Y’);
} ?>
谁有24小时内倒序显示时间的方法分享一下,谢谢!
以上function.php部分代码由万戈修改:http://wange.im/show-time-since-in-wordpress.html
THE END







为什么放到function.php 里面就打不开页面.....
加到function里得时候前后的php ?>要去掉。
那个已经过时了,看这个http://muxer.cn/625.html
越来越感觉到最好的内容都是来自博客。好久都不逛论坛了。
从万兄那跑来深究~~
这个想法不错,有点像论坛回复时间的样子了,呵呵
要不你去整一个出来分享下?!
今天从gg reader中回顾了这篇日志,刚刚整出来了~
http://wange.im/show-time-since-in-wordpress.html