WordPress Improved Human Time Difference

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();

Let me know what you think 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.

WordPress News

The latest WordPress updates from the WPBriefs Podcast.

Related Posts

04 Nov 2006

WordPress Tips and Tricks – Post in Advance

I’m sure most people know about this but the ability to post things in advance with WordPress is absolutely great. My two blogs (this one and Binary Joy) posted 16 articles whilst I was on holiday despite me not being...
27 Sep 2016

Schedule content with Automatic Post Scheduler

Posting regular content is essential when you’re trying to build a successful blog or website – but it’s something I struggle with. I think I’ve found a solution that works for me though. Regular content is great for Google (and...
19 Jun 2008

Redesigning the WordPress admin Redesign

Ever since the first betas of WordPress 2.5 I have been making my own version of the admin panel. I like a lot of what they have done but there were some very basic things missing in the design, and...
20 Jul 2016

Empathy in Web Design

I wasn’t able to make WordCamp Europe this year, but they’ve been really quick at getting all of the talks online, and so I have been watching some of them – and this one stood out.Morten Rand-Hendriksen is an experienced...
27 May 2013

WordPress: 10 Years Young, What Does The Future Hold?

WordPress is now 10 years old. I started using wordpress 9 years ago – which means I joined the WordPress community early on. The reason I chose WordPress is simply because of the fabled 5 minute install process – I...