Facebook style “Time Ago” for WordPress

Written by pelister. Posted in Wordpress

The last “Time Ago” function is short of few things, how about facebook style “Time ago” for posts and comments in wordpress. The last function that I wrote didn’t calculate for years, for example if I like to display “2 years ago” for a post published 2 years ago, it displayed “730 days ago”, which I didn’t like. So I have come up with a new function which will work for the following – Seconds, Minutes, Hours, Weeks, Months and Years.

open your functions.php and paste this code, a complete function that will return the “time ago” output .
function timeago()
{
   global $post;

   $unix_date = get_post_time('U', true, $post);

   $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
   $lengths = array("60","60","24","7","4.35","12","10");

   $now             = time();
   
   // check validity of date
   if(empty($unix_date)) {   
       return "Bad date";
   }

   // is it future date or past date
   if($now > $unix_date) {   
        $difference     = $now - $unix_date;
        $tense         = "ago";

   } else {
        $difference     = $unix_date - $now;
        $tense         = "from now";
   }

   for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
        $difference /= $lengths[$j];
   }

   $difference = round($difference);

   if($difference != 1) {
        $periods[$j].= "s";
   }

   return "$difference $periods[$j] {$tense}";
}

Now save your functions.php and wherever you want to display time ago just add this line

<?php echo timeago(); ?>

You can insert into category.php, single.php to display the time elapsed since the post was published. This function right now works for posts alone, soon I will publish with time elapsed display for comments too.

Popular Posts

Techlister© - 2012