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.
A Nifty WordPress Script
The human_diff_time() function determines the difference between two timestamps and looks like this:
<?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:
You will need to replace it with the following line of code:
echo 'Posted ' . human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago ';
And here’s what it looks like:
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.Tags: