Last active
August 29, 2015 14:05
-
-
Save danielhomer/a54d08cc7eff2296b034 to your computer and use it in GitHub Desktop.
WordPress pretty timestamp function. 'Posted 1 day ago' / 'Posted 2 hours ago' etc.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Echoes a pretty timestamp if the post is younger than max_days. | |
* Must be used inside the loop. | |
* | |
* Examples: | |
* - Posted 3 days ago | |
* - Posted 12 hours ago | |
* - Posted 5 minutes ago | |
* - Posted just now (less than a minute ago) | |
* - 2014-07-25 08:33:54 (post is older than $max_days) | |
* | |
* @param integer $max_days The maximum age of the post before reverting to | |
* traditional timestamps. | |
*/ | |
function the_pretty_timestamp( $max_days = 7 ) { | |
$post = get_post(); | |
$one_day = 60 * 60 * 24; | |
$one_hour = 60 * 60; | |
$one_minute = 60; | |
$post_age = current_time( 'timestamp' ) - strtotime( $post->post_date ); | |
if ( ! is_numeric( $post_age ) || ( $post_age / $one_day ) > $max_days ) { | |
echo $post->post_date; | |
return; | |
} | |
$days = round( $post_age / $one_day ); | |
$hours = round( $post_age / $one_hour ); | |
$minutes = round( $post_age / $one_minute ); | |
if ( $days >= 1 ) { | |
echo 'Posted ' . $days . ' day' . ( $days > 1 ? 's' : '' ) . ' ago'; | |
} else if ( $hours >= 1 ) { | |
echo 'Posted ' . $hours . ' hour' . ( $hours > 1 ? 's' : '' ) . ' ago'; | |
} else if ( $minutes >= 1 ) { | |
echo 'Posted ' . $minutes . ' minute' . ( $minutes > 1 ? 's' : '' ) . ' ago'; | |
} else { | |
echo 'Posted just now'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment