0

I'm looking at getting a "posted 2 days, 16 hours, 3 minutes etc ago" etc style of timestamp on Wordpress posts, and Glavic's code here looked interesting.

Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...

function time_elapsed_string($datetime, $full = false) {
$now = new DateTime;
$ago = new DateTime($datetime);
$diff = $now->diff($ago);

$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;

$string = array(
    'y' => 'year',
    'm' => 'month',
    'w' => 'week',
    'd' => 'day',
    'h' => 'hour',
    'i' => 'minute',
    's' => 'second',
);
foreach ($string as $k => &$v) {
    if ($diff->$k) {
        $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
    } else {
        unset($string[$k]);
    }
}

if (!$full) $string = array_slice($string, 0, 1);
return $string ? implode(', ', $string) . ' ago' : 'just now'; 
}

What parts do I modify to receive Wordpress's the_date function (if that's the correct one) and a Unix timestamp?

Thanks!

1 Answers1

0

The function you have provided expects a date string.

Wordpress has a function to retrieve the date of a post called get_the_date()

Only thing you need is to actually combine those two together in a more less this way: echo time_elapsed_string(get_the_date(), true) and place this line within post template code.

Owi
  • 488
  • 2
  • 7