WordPress Relative Post Time

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!

This entry was posted in how to and tagged , . Bookmark the permalink.

4 Responses to WordPress Relative Post Time

  1. JoE says:

    This was an amazing find! Exactly what I needed. Thank you.

  2. JoE says:

    This was an amazing find! Exactly what I needed. Thank you.

  3. No problem, glad it helped!

  4. No problem, glad it helped!