学做网站培训课程介绍

当前位置:

WordPress 文章日期显示方式“xx以前”

WordPress 普通的调用日期代码为:


<?php get_the_time('Y-m-d G:i:s');?>

显示格式为:2030年8月8日 21:16:15

但在有些地方,我们做网站时,要显示的日期格式为“xx以前”,如下图:

Wordpress 文章日期显示方式“xx以前”

要显示“xx以前”格式,可以使用下面的代码来实现。

第一步:将以下的代码粘贴到functions.php函数文件里;


//时间显示方式‘xx以前’
function time_ago( $type = 'commennt', $day = 7 ) {
$d = $type == 'post' ? 'get_post_time' : 'get_comment_time';
if (time() - $d('U') > 60*60*24*$day) return;
echo ' (', human_time_diff($d('U'), strtotime(current_time('mysql', 0))), '前)';
}
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 echo timeago( get_gmt_from_date(get_the_time('Y-m-d G:i:s')) )?>

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

相关教程