WordPress文章发布日期(时间)美化之怎么显示成xx以前

追格官方小助手/ 2022年03月06日/ WordPress/ 浏览 1800


WordPress文章日期常见显示格式为2022年03月06日 10:30:30,若想显示成xx以前,应该怎么处理?


1、将以下的代码放到当前WordPress主题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;
}
};
}


2、相应位置调用下面代码即可;


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


发表评论

暂无评论,抢个沙发...

客服 工单