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/lSFWmpHTX1 Patrick Stewart talks about meeting Sting on the set of DUNE (Funny to the EXTREME)

Shaun Freeman @Zendmaster

I added a video to a @YouTube playlist https://t.co/pmXSmod4ti Anonymous - This will Change Everything You Know... (2018-2019)

Shaun Freeman @Zendmaster

I added a video to a @YouTube playlist https://t.co/GkwTCvBfes Will Artificial Intelligence Take Over The World?

Shaun Freeman @Zendmaster

I liked a @YouTube video https://t.co/Y1ulafmsC6 Frank Abagnale: "Catch Me If You Can" | Talks at Google

Shaun Freeman @Zendmaster

I liked a @YouTube video https://t.co/NBdW2xFnqD ETS2: Special Transport DLC Trailer