How to Timestamp Your Posts Like Twitter and Facebook

Here’s a handy WordPress script you might not know about.

Did you know WordPress has a built-in function to display relative time in a human-readable format, just like Twitter and Facebook? For example, instead of your posts displaying, “Posted on January 23 at 10.30am,” you could display, “Posted 5 hours ago.”

In this Weekend WordPress Project I’ll show you how to update the Twenty Fourteen theme to take advantage of the human_time_diff() function and change the timestamp on your posts.

Feature image

A Nifty WordPress Script

The human_diff_time() function determines the difference between two timestamps and looks like this:

1
<?php human_time_diff( $from, $to ); ?>

I was surprised to discover this function exists, especially since it has been been part of WordPress core since version 1.5.

So how do you use it?

For todays’ project we’re going to replace the timestamp above posts in the Twenty Fourteen theme with a relative time, so first we’ll need to create a child theme. Check out my post How to Create A Child Theme if you’re not sure how to do this.

Once you’ve done that, make sure you’ve got a copy of the functions.php file in your child theme and open it up. Look for the line:

1
twentyfourteen_posted_on();

You will need to replace it with the following line of code:

1
echo 'Posted ' . human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago ';

And here’s what it looks like:

WordPress Relative Timestamp
The human_time_diff() function allows you to display timestamps in your posts that are easy to read.

If you want to keep the date and add a relative time after it, you should leave the twentyfourteen_posted_on function and immediately after it add the human_diff_time function.

Have fun with this function and have a great weekend!

Do you use relative times on your site? Tell us in the comments below.

Comments (4)

    • Yes, you can definitely implement this using other themes, you just need to find the snippet of code that displays the timestamp. Every theme is different, for example Twenty Thirteen uses the twentyfourteen_posted_on() function.

  1. I couldn’t find the line “twentyfourteen_posted_on()” in the functions file. I did find it in “/inc/template-tags.php”

    The posted on date is tied in with the post meta data:

    printf( ‘%3$s %5$s‘, esc_url( get_permalink() ),
    esc_attr( get_the_date( ‘c’ ) ),
    esc_attr( get_the_date() ),
    esc_url( get_author_posts_url( get_the_author_meta( ‘ID’ ) ) ),
    get_the_author()
    );

    It’s it’s not too hard to work out. I just replaced ‘%3$s’ with ‘Posted %3$s ago’ and the second call to ‘get_the_date()’ with ”human_time_diff()’.

Participate