Skip to content

Instantly share code, notes, and snippets.

@ThatGuySam
Created August 13, 2016 13:57
Show Gist options
  • Save ThatGuySam/b0affaa01c1b2a36a4096118de30c78f to your computer and use it in GitHub Desktop.
Save ThatGuySam/b0affaa01c1b2a36a4096118de30c78f to your computer and use it in GitHub Desktop.
Clean looking post times for Wordpress
<!--Example-->
<?php echo cleanPostDate( get_the_date( 'U' ) ); ?>
<?php echo cleanPostDate( get_the_date() ); ?>
<?php
function cleanPostDate($arg_post_date) {
//Detect if it's already UTC
if( true == is_numeric($arg_post_date) && 0 != $arg_post_date ){
//Post date is good to go
$post_date = $arg_post_date;
} else {//Parse non-UTC date int UTC
//Try to read post date an time string
$post_date = strtotime( $arg_post_date );
}
//If it's still not valid then stop
if( false == $post_date || 0 == $post_date ){ return false; }
$wordpress_local_time = current_time( 'U' );//Local time in wordpress
$an_hour = 60 * 60;//60 seconds times 60 minutes
$a_day = $an_hour * 24;
//debug( $post_date >= strtotime( '1 hour ago', $wordpress_local_time ) );
if( $post_date >= strtotime( '-1 hour', $wordpress_local_time ) ){//If less than 1 hour hours
//Minute Format - 5 min ago
$minutes_since = round( abs($wordpress_local_time - $post_date) / 60 );
$output_date = $minutes_since.' mins ago';
} else if( date('d/m/Y', $post_date ) == date('d/m/Y', $wordpress_local_time) ){//If it's from today
//Hour Format - 5 hrs ago
$hours_since = round( abs($wordpress_local_time - $post_date) / (60 * 60) );
$output_date = $hours_since.' hrs ago';
} else if( date('d/m/Y', $post_date ) == date('d/m/Y', $wordpress_local_time - $a_day) ){//If Yesterday
$output_date = 'Yesterday';
} else if( date('W/Y', $post_date ) == date('W/Y', $wordpress_local_time) ){//If from this week
//Format - Sunday
$output_date = date('l', $post_date );
} else if( date('Y', $post_date ) == date('Y', $wordpress_local_time) ){//If from this year
//Format - August 8
$output_date = date('F j', $post_date);
} else {//Pretty much if it's older than this year
//Format - August 8 1992
$output_date = date('F j Y', $post_date);
}
//19 hrs ago(If less than 24 hours)
//Yesterday(If date is yesterday)
//2 days ago(If from this week)
//Aug 3(If from this year)
//Dec 31st 2015(If all else)
return $output_date;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment