WordPress 显示发布内容于多少时间前

这个标题很难表达我想要显示的效果,所以大家可以先去我的“给我留言”页面看一下,请注意留言时间的显示格式,细心的童鞋已经发现了,在24小时以内发布的留言会显示成“**时间 前”这样的格式,而发布超过24小时的评论则如往常一样显示时间格式。这让你想到了什么?对,没错,就是论坛,比较人性化的一个效果。这个效果要感谢 happyet 童鞋,因为此方法就是修改于他的文章:《换个方式显示日志发表时间和回复时间》,正好我也借此机会解答了他在文中的问题,并且小小的扩展一下。

首先在 WordPress 主题文件夹下的 functions.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');
            }
    }
?>

函数定义好了,接下来就是在需要的地方调用此函数即可。

先说说我用到的函数,我是在 WordPress 的评论中用到这个效果,那就在 functions.php 中的 mytheme_comment() 函数中找到评论日期显示的代码:

<?php printf(__('%1$s at %2$s'), get_comment_date(),  get_comment_time()) ?>

如果你还只是符合 WordPress 2.7 以下的主题,那就在 comments.php 中找到这句代码。然后用以下代码替换:

<?php if (function_exists('time_since')) {
echo time_since(abs(strtotime($comment->comment_date_gmt . "GMT")), time());
}
?>

如果你还想要使发布的 WordPress 日志也有这样的时间显示格式,那就在 index.php、single.php 等文件中找到相应的时间函数,并用以下代码替换:

<?php if (function_exists('time_since')) {
echo time_since(abs(strtotime($post->post_date_gmt . "GMT")), time());
}
?>

另外,你可能已经注意到了右上角 Twitter 最新消息那里,我也用到了这个效果,用过 Twitter 的童鞋应该知道,Twitter 本身就是这样显示发布消息的时间,这样一来就和 Twitter 更像了吧,呵呵。

更多的应用效果就留给同学们自己去开发挖掘吧,欢迎留言试,也欢迎刷新本页看变化的时间格式。