WordPress has a built in function, called human_time_diff, for creating messages that say how long ago a post was published – however I think it is confusing when you have posts from a long time ago that read “posted 15 months ago” since you then have to calculate the date.
So I thought I’d make an enhanced version of human_time_diff that checks how long ago the post was published and changes to the publication date if the post is older than 60 days. This way you get the nice clean ‘3 hours ago’ style message – or the clearer date listing on older content.
function bm_human_time_diff_enhanced( $duration = 60 ) {
$post_time = get_the_time('U');
$human_time = '';
$time_now = date('U');
// use human time if less that $duration days ago (60 days by default)
// 60 seconds * 60 minutes * 24 hours * $duration days
if ( $post_time > $time_now - ( 60 * 60 * 24 * $duration ) ) {
$human_time = sprintf( __( '%s ago', 'binarymoon'), human_time_diff( $post_time, current_time( 'timestamp' ) ) );
} else {
$human_time = get_the_date();
}
return $human_time;
}
//usage
echo bm_human_time_diff_enhanced();
Was it good/ useful/ a load of old rubbish? Let me know on Mastodon, or BlueSky (or Twitter X if you must).
Link to this page
Thanks for reading. I'd really appreciate it if you'd link to this page if you mention it in your newsletter or on your blog.