Skip to content

Instantly share code, notes, and snippets.

@Vesymos
Created November 11, 2014 10:48
Show Gist options
  • Save Vesymos/9760fc20b013b1808b13 to your computer and use it in GitHub Desktop.
Save Vesymos/9760fc20b013b1808b13 to your computer and use it in GitHub Desktop.
Display how long ago a comment, post or item was published. From: https://kopepasah.com/tutorial/display-how-long-ago-a-comment-post-or-item-was-published/ Usage: <?php get_time_difference( $comment->comment_date ); ?>
<?php
/**
* Return a time difference of a given time in
* days, hours or minutes depending on the time
* difference.
*
* @param $time (required)
*/
function get_time_difference( $time ) {
$current_time = new DateTime( current_time( 'mysql' ) );
$previous_time = new DateTime( $time );
$difference = $current_time->diff( $previous_time );
$timestamp = '';
if ( 0 < $difference->y ) {
$timestamp = get_the_date( 'F j, Y' );
} else if ( 12 >= $difference->m && 1 <= $difference->m ) {
$timestamp .= get_the_date( 'F j' );
} else if ( 0 < $difference->d ) {
$timestamp .= sprintf( translate_nooped_plural( _n_noop( '%s Day Ago', '%s Days Ago' ), $difference->days ), $difference->days );
} else if ( 0 < $difference->h ) {
$timestamp .= sprintf( translate_nooped_plural( _n_noop( '%s Hour Ago', '%s Hours Ago', 'listed' ), $difference->h, 'listed' ), $difference->h );
} else if ( 0 < $difference->i ) {
$timestamp .= sprintf( translate_nooped_plural( _n_noop( '%s Minute Ago', '%s Minutes Ago', 'listed' ), $difference->i, 'listed' ), $difference->i );
} else {
$timestamp = __( 'Just Now', 'listed' );
}
return $timestamp;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment