This is a small function I wrote this morning to generate relative time stamps for WordPress posts, similar to those used on Twitter. It is pretty simple to implement, and will allow you to display a relative timestamp simply by replacing the <?php post_date(); ?> call with <?php relative_time(); ?> in your theme.
What it does
This function displays one of the following, depending on the time since the post was published:
- “Less than a minute ago”
- “About a minute ago”
- “XX minutes ago”
- “About an hour ago”
- “XX hours ago”
- The date in the format “Day Month Year Time” (12 hour)
Implementation
Simply add the following code to the functions.php file of your theme:
<?php
function relative_time() {
$post_date = get_the_time('U');
$delta = time() - $post_date;
if ( $delta < 60 ) {
echo 'Less than a minute ago';
}
elseif ($delta > 60 && $delta < 120){
echo 'About a minute ago';
}
elseif ($delta > 120 && $delta < (60*60)){
echo strval(round(($delta/60),0)), ' minutes ago';
}
elseif ($delta > (60*60) && $delta < (120*60)){
echo 'About an hour ago';
}
elseif ($delta > (120*60) && $delta < (24*60*60)){
echo strval(round(($delta/3600),0)), ' hours ago';
}
else {
echo the_time('j\<\s\u\p\>S\<\/\s\u\p\> M y g:i a');
}
}
?>
You can now display the relative time of a post by adding the following anywhere within the loop:
<?php relative_time(); ?>
That’s it really, hopefully it will prove useful to somebody!
2 Comments
24th June 2010
7:33 am
Hi, got to your blog when searching for the exact same feature. However I found out that WordPress already has a function for that: human_time_diff()
useful function:
function time_ago( $type = ‘post’ ) {
$d = ‘comment’ == $type ? ‘get_comment_time’ : ‘get_post_time’;
return human_time_diff($d(‘U’), current_time(‘timestamp’)) . ” ” . __(‘ago’);
}
Thanks
16th September 2011
5:10 am
Thank you very much for your function. Your function is even more humanise than human_time_diff().
I will modify it a bit to accept custom date time format.