我们在浏网站或论坛的时候,经常会看到此文章或评论发布于几分钟前、几小时前、几天前这样的微时间格式,那么在wordpress中显示这种格式的时间该如何实现呢?
方法一:添加 filter 方式
WordPress默认调用的是the_time()函数,可以通过给the_time()添加一个 filter来显示微时间,在 function.php 文件中添加如下代码。
- function timeago(){
- $time_diff = current_time('timestamp') - get_the_time('U'); //计算两个日期之间的秒数差
- if ($time_diff <= 86400 * 7) { // 判断日期差是否在一周之内
- if ($time_diff <= 300) { //5分钟之内
- echo '刚刚'; //显示刚刚
- } elseif ($time_diff <= 86400) { //24小时之内
- echo human_time_diff(get_the_time('U'), current_time('timestamp')) . '前'; //显示几小时前
- } else {
- $days = 0;
- if (get_the_time('m') != current_time('m')) { // 如果不跨月
- $days = daysInmonth1(get_the_time('y'), get_the_time('m')); // 计算上个月总共有多少天
- }
- $s = current_time('d') + $days; // 计算天数差时要加上上个月的总天数
- $m = get_the_time('d');
- if ($m == $s - 1) {
- echo '昨天'; // 显示昨天
- } else {
- echo $s - $m - 1 . '天前'; //显示几天前
- }
- }
- } else {
- if (get_the_time('Y') == current_time('Y')) {
- echo the_time('m月d日');
- } else {
- echo the_time('Y年m月d日');
- }
- }
- }
- add_filter('the_time',timeago');
方法二:新定义函数
首先,在我们所使用主题的 functions.php 新定义一个方法。
- function timeago( $stime ) {
- date_default_timezone_set ('ETC/GMT');
- $ptimes = strtotime($stime);
- $etime = time() - $ptimes;
- if ($etime < 1) {
- $time = '刚刚';
- }elseif($etime < 60){
- $time = sprintf('%s 分钟前', $etime);
- } elseif ($etime < 1440) {
- $time = sprintf('%s 小时前', round($etime / 60));
- } else {
- $time = date("Y-m-d",$ptimes);
- }
- return $time;
- }
或者
- function timeago( $ptime ) {
- date_default_timezone_set ('ETC/GMT');
- $ptimes = strtotime($ptime);
- $etime = time() - $ptimes;
- 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'))); ?>
评论发布时间格式修改使用方法:
把原先显示时间的代码改为以下代码即可:
- <?php echo timeago(get_gmt_from_date(get_comment_date('Y-m-d G:i:s'))); ?>
本文已通过「原本」原创作品认证,转载请注明文章出处及链接。