Display Post Date in “Time Ago” Format

In order to display the post date we generally use the_time function on our template files. However, if you are interested to display the in “Time Ago” format that you may have seen on other websites, there is a simple WordPress function (human_time_diff) that we can use. This is how it works.

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

What we are doing here is pretty simple. We are taking two parameters. The first one is the get_the_time function that retrieves the post published date from the database. Also note that we are using “U” as we want to get the post published date in Unix time format.

Another parameter is the current_time function that retrieves the current time of the server. However, just like before we are using “timestamp” to get the Unix time format. At the end we are simply displaying the “ago” text with the result.

Note: This snippet works pretty well within the WordPress loop. So basically you can use it within the regular or custom loop. Either way it should work without any hiccups.

Today In History



Leave a Reply

Note: Convet HTML, PHP, JavaScripts from HTMLify, before posting from comment section.
License: By submitting a comment here you grant this site a perpetual license to reproduce your words and name/Web site in attribution. Please use your real name or a pseudonym (i.e., pen name, alias, nom de plume) when commenting. If you add your site name, company name, or something completely random, I'll likely change it to whatever I want.