不亦乐乎 » Wordpress » 换个方式显示日志发表时间和回复时间

换个方式显示日志发表时间和回复时间

2010年01月14日 1,965人路过 参与围观5人围观

update 下文代码已经修改,可以实现人性化显示日志和回复的发表时间

通常的日志发表时间都显示为年月日的形式,这个方法是把它改成显示为几小时前、几天前或者几年前的形式,如我测试的时候是显示为This entry was posted 9 months ago,然后将回复的时间改成日志发表后多长时间回复的形式。代码是一个老外的博客上看到的,我测试了可以用,不过我是想时间超过24小时就显示为正常的年月日,可是本人不懂php,不知道怎么修改,只好放弃不用,发出来给感兴趣的人用了。

在主题文件夹下的function.php文件里最底部的 ?>前加入以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?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');
            }
    }
?>

然后在你需要显示时间的地方用下面的代码替换,日志部分:

1
2
3
4
5
<?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默认的,只有单独写代码的才有的改):

1
2
3
4
5
<?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

无觅相关文章插件,快速提升流量

分类:Wordpress, 标签:, ,
你可以通过 RSS 2.0 订阅关注本日志评论, 也可以直接 参与围观, 或 trackback 到你的博客上.
本日志地址: http://www.happyet.org/357.html, 转载请注明出处!

“换个方式显示日志发表时间和回复时间”上有 5 条评论

  1. 万戈 说道:

    这个想法不错,有点像论坛回复时间的样子了,呵呵

  2. 超人 说道:

    从万兄那跑来深究~~

  3. The7in 说道:

    越来越感觉到最好的内容都是来自博客。好久都不逛论坛了。

留下足迹