4

wordpress by default writes the the date on posts, but how can I transform it to : "x" time ago ?? like 3 days ago, or 5 minutes ago ??

2
function k99_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');
    }
}

then put k99_relative_time(); in theme file where you want this to appear.

5

Wordpress has a built-in funtion called human_time_diff() that allows you to do this.

Just place this code in your functions.php

function time_ago( $type = 'post' ) {
    $d = 'comment' == $type ? 'get_comment_time' : 'get_post_time';

    return human_time_diff($d('U'), current_time('timestamp')) . " " . __('ago');

}

To use it anywhere in your theme (for example, on single.php), place this code where you want the "time ago" feature displayed:

<?php echo time_ago(); ?>

Let me know if it worked for you.

  • thanks, it is good to know that this function exists . however, krembo99´s solution gives a bit more flexibility on the output format ... also, he posted first, and I can accept only one .. – user13279 Dec 12 '11 at 16:01
  • 1
    well, I voted up - I did not knew of this function myself ... – krembo99 Dec 12 '11 at 16:05
  • @krembo99 Nice! Your solution isn't bad and works well. I tested it. – Sosthenes Kwame Boame Dec 12 '11 at 16:08
  • @obmer kronen, no problem. Maybe you can use it another time or someone else might find it useful. Always a pleasure to share. – Sosthenes Kwame Boame Dec 12 '11 at 16:09
  • That's a cached fn. Won't work in every case. – kaiser Dec 12 '11 at 17:02

protected by Community Sep 18 '16 at 7:50

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?