Wordpress Relative Post Time

by Andy Appleton

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!