Relative Time On Posts

I am looking for a way that I could add some code to my wordpress template to display the time of a post in relative terms. So if, for example, I posted something 5 minutes ago it would say something along the lines of Posted 6 minutes ago or 2 days ago, or 1 week ago. You get the idea. Could anyone give me some guidance on how I could go about doing this?

2 Answers
2

WordPress actually has an obscure and little known function called human_time_diff() that does this. It takes two arguments; the first is the earlier timestamp, and the second is the later timestamp. Both should be Unix timestamps. The first argument is required, but the second is optional, and will use time() if left empty. So, for example, in the loop, you could do this:

<p>Posted <?php echo human_time_diff( get_the_time( 'U' ) ); ?> ago.</p>

The function will only do minutes, hours, and days, though. If you need to get weeks, for example, you could do something like this:

$diff = explode( ' ', human_time_diff( get_the_time( 'U' ) ) );
if( $diff[1] == 'days' && 7 <= $diff[0] ){
  $diff[1] = 'week';
  $diff[0] = round( (int)$diff[0] / 7 );
  if( $diff[0] > 1 )
    $diff[1] .= 's';
  $diff = implode( ' ', $diff );
}

That would give you N week(s) as a string.

Leave a Comment