Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Convert get_comments->comment_date in relative date WordPress

  • SOLVED

In my index.php, I'd like to display some details about last comment for each post...

some thing like:

<strong>Last reply by user_name - 2 hours ago </strong>

Now with this code I'm able to display :

<em>Last reply by user_name - 2011-07-29 11:23:31</em>

$comments = get_comments('post_id=' . $post->ID . '&number=1');
if($comments) {
foreach($comments as $comment) :
echo('Last reply by '. $comment->comment_author .
' - ' . $comment->comment_date);
endforeach;
}


How can I achieve it?

Just FYI

For timestamps within the looop for both post and comments I can use this function to do so:

if(!function_exists('how_long_ago')){
function how_long_ago($timestamp){
$difference = time() - $timestamp;

if($difference >= 60*60*24*365){ // if more than a year ago
$int = intval($difference / (60*60*24*365));
$s = ($int > 1) ? 's' : '';
$r = $int . ' year' . $s . ' ago';
} elseif($difference >= 60*60*24*7*5){ // if more than five weeks ago
$int = intval($difference / (60*60*24*30));
$s = ($int > 1) ? 's' : '';
$r = $int . ' month' . $s . ' ago';
} elseif($difference >= 60*60*24*7){ // if more than a week ago
$int = intval($difference / (60*60*24*7));
$s = ($int > 1) ? 's' : '';
$r = $int . ' week' . $s . ' ago';
} elseif($difference >= 60*60*24){ // if more than a day ago
$int = intval($difference / (60*60*24));
$s = ($int > 1) ? 's' : '';
$r = $int . ' day' . $s . ' ago';
} elseif($difference >= 60*60){ // if more than an hour ago
$int = intval($difference / (60*60));
$s = ($int > 1) ? 's' : '';
$r = $int . ' hour' . $s . ' ago';
} elseif($difference >= 60){ // if more than a minute ago
$int = intval($difference / (60));
$s = ($int > 1) ? 's' : '';
$r = $int . ' minute' . $s . ' ago';
} else { // if less than a minute ago
$r = 'moments ago';
}

return $r;
}
}


and this 2 snippets for post and comments

//post:
if(!function_exists('how_long_ago')){the_time('F jS, Y'); } else { echo how_long_ago(get_the_time('U')); }

//comments:
if(!function_exists('how_long_ago')){the_time('F jS, Y'); } else { echo how_long_ago(get_comment_time('U')); }


But I 'm unable to use this for the above case...

Anyone can help?

Answers (2)

2011-07-29

Hai Bui answers:

Please try this:
$comments = get_comments('post_id=' . $post->ID . '&number=1');

if($comments) {

foreach($comments as $comment) :

echo('Last reply by '. $comment->comment_author .

' - ' . how_long_ago(strtotime($comment->comment_date)));

endforeach;

}


gino naya comments:

works like a charm!
Thanks,
Paolo

2011-07-29

Sébastien | French WordpressDesigner answers:

[[LINK href="http://codex.wordpress.org/Function_Reference/human_time_diff"]]http://codex.wordpress.org/Function_Reference/human_time_diff[[/LINK]]