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

I liked a @YouTube video https://t.co/8nGfvmdsI2 From Carnivore Diet to Near-Death: Lessons Learned From Today's Most Popular Fad Diet

Shaun Freeman @Zendmaster

I liked a @YouTube video https://t.co/EFLh2y3I24 Carnivore Diet – Myths about Meat – Phil Escott – WHIS 2018

Shaun Freeman @Zendmaster

I liked a @YouTube video https://t.co/dTcBFM4q5A WHY I STOPPED BEING VEGAN | MY STORY

Shaun Freeman @Zendmaster

I liked a @YouTube video https://t.co/RVuVCieSsD Dr. Paul Mason - 'Low Carb from a Doctor's perspective'

Shaun Freeman @Zendmaster

I added a video to a @YouTube playlist https://t.co/MFRRuBG23F It's Already Too Late - Elon Musk