Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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 ??

share|improve this question
add comment

3 Answers

up vote 2 down vote accepted
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.

share|improve this answer
add comment

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.

share|improve this answer
    
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. –  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. –  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
show 1 more comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.