How to display time in “time ago” format

By default, WordPress will put a timestamp on each and every article that you publish. This is by any means a must-have feature. Imagine yourself reading an article without a timestamp – you wouldn’t be quite comfortable reading news for which you can’t tell if they’re a day or a month old, right?

While there’s nothing wrong with the usual timestamp on WordPress posts, sometimes you want to show the amount of time which has passed after the post was published.

Somehow, if you can read that the post was published 5 minutes ago, 5 hours ago or 5 weeks ago feels more personal and much more pleasant than reading the date.

Instead of checking the current date and counting the days, the post can tell you how long it was public. And what most people don’t know is that WordPress already has a built-in function which can calculate the human time difference.

<?php echo human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ago'; ?>

This little function takes two post timestamps and calculates the time between them. It will take the time it was stamped on a post after it was published and the current time on your machine so it can show you the difference. The result is a time shown in minutes, hours, weeks, months and years which have passed after the post became public.

Now that you have decided that you really want this kind of timestamp in your posts, we will show you how to implement the function. Don’t worry, there’s nothing much to do. Since you probably want to show the stamp in your posts, you will need to edit the file which contains information about your posts:

  1. Open single.php file
  2. Copy and paste the following code and place it anywhere you want the timestamp to appear; for example, right after the header:
  3. I wrote this awesome article <?php echo human_time_diff(get_the_time(‘U’), current_time(‘timestamp’)) . ‘ ago’; ?>

  4. Change the message before the code
  5. Save changes

Now you can go on and test the code. Open any published post and find the new timestamp right underneath your header (if you have placed the code below the header, of course). Play around until you find the best place to show the “time ago” stamp, style it and enjoy your new feature.

START YOUR OWN BLOG

This guide is an introduction to mastering the art of blogging. It provides easy to follow steps to start, maintain, and grow your blog.

Read the guide

Leave a Reply

Your email address will not be published. Required fields are marked *