While developing a custom site I was in a need to represent how many minutes/hours/days the post was published ago instead of the published date.
The logic of the code is simple:
TIME | DISPLAY |
less than 1 hour | XX minutes ago |
1 – 24 hours | XX hours ago |
24 hours – 7 days | XX days ago |
more than 7 days | default time |
Code snippet:
function Bing_filter_time() {
global $post ;
$to = time();
$from = get_the_time('U') ;
$diff = (int) abs($to - $from);
if ($diff <= 3600) {
$mins = round($diff / 60);
if ($mins <= 1) {
$mins = 1;
}
$time = sprintf ( _n ( '%s minutes' , '%s minutes' , $mins ) , $mins ) . __ ( 'Front' , 'Bing' ) ;
} else if (($diff <= 86400) && ($diff > 3600)) {
$hours = round($diff / 3600);
if ($hours <= 1) {
$hours = 1;
}
$time = sprintf ( _n ( '%s hours' , '%s hours' , $hours ) , $hours ) . __ ( 'Front' , 'Bing' ) ;
} elseif ($diff >= 86400) {
$days = round($diff / 86400);
if ($days <= 1) {
$days = 1;
$time = sprintf ( _n ( '%s days' , '%s days' , $days ) , $days ) . __ ( 'Front' , 'Bing' ) ;
} elseif ($days > 29) {
$time = get_the_time(get_option('date_format'));
} else {
$time = sprintf ( _n ( '%s days' , '%s days' , $days ) , $days ) . __ ( 'Front' , 'Bing' ) ;
}
}
return $time;
}
add_filter('the_time','Bing_filter_time');
Was this post helpful?
Let me know if you liked the post. That’s the only way I can improve. 🙂
where do you paste this code?
Place this code inside your active theme’s functions.php file, just under the opening php tag
or even better, create a child theme first.