Wordpress - Relative Dates for Posts and Comments

Wordpress - Relative Dates for Posts and Comments

I come across a little tip the other day from Relative dates for posts and commentsin wordpress to get your Wordpress posts date in a relative time format, like Twitter (1 min, 1hour, 1day ago), anyway you know what I mean.

The trick is to add a filter and function to you themes function file, so in your Wordpress admin go to 'Appearance > Editor' and choose your current theme, on the right there is a list of page in your theme click on the Theme Functions one (functions.php). and add:

// For posts
add_filter( 'get_the_date', 'human_get_the_date' );
// For comments
add_filter( 'get_comment_date', 'human_get_the_date' );

function human_get_the_date ($date) {
    return human_time_diff( strtotime($date) ) . ' ago';
}

But there seemed to be a error in this it was returning my date/time from as though I wrote it at midnight, as the post at Revood was written in 2011 so I thought it might be a little out of date, so a little digging on Google and I found the answer to be in the human_time_diff function, this function takes two arguments, the 'form date' and the 'to date' so the trick is to get the time that the post was published and subtract the current time from that, now we don't need to do this as Wordpress has the function human_time_diff which does it for us so the updated snippet:

// For posts
add_filter( 'get_the_date', 'human_get_the_date' );
// For comments
add_filter( 'get_comment_date', 'human_get_the_date' );

function human_get_the_date () {
    return human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago';
}

Now I have relative date/times on my post.

Hope you enjoy!


20/04/2014 19:32:00 Shaun Freeman Filed Under: WordPress PHP, WordPress

Twitter Feed
Shaun Freeman @Zendmaster

Shaun Freeman @Zendmaster

Banished LP #1 - Humble Beginnings: https://t.co/5riUkijyLq via @YouTube

Shaun Freeman @Zendmaster

Installing Banished on Ubuntu 18.04: https://t.co/5judq1fMSc via @YouTube

Shaun Freeman @Zendmaster

Setting Up A Test Environment For PHP In VirtualBox - Part 4 Installing PHP: https://t.co/UDRLhjiJFb via @YouTube

Shaun Freeman @Zendmaster

Setting Up A Testing Environment For PHP Using VirtualBox - Part 4 Installing MySQL https://t.co/huVfEcr6jS

Shaun Freeman @Zendmaster

I liked a @YouTube video https://t.co/n8zIhpTH3I Windows Games on Linux with Valve's Proton - with The Linux Gamer