Show Relative Timings In WordPress

You would have seen WordPress websites displaying relative timings for post entries, i.e., 2 hours ago, 5 days ago, 1 month ago, etc. This can be done very easily, but you need to have some basic knowledge about PHP. Make sure you don’t make any typing errors while editing the PHP files, a single error in any PHP file will prevent your website from loading.

You can use this code anywhere within the loop. This will print the relative time (difference between the time of publishing the post and the time when the webpage loaded).

printf( _x( '%s ago', '%s = human-readable time difference', 'text-domain' ), human_time_diff( get_the_time('U'), current_time('timestamp') ) );

Change the blue colored text with the text domain of your theme. This is used for internationalization of the theme.

One thing to note here is that if you use a cache plugin, a wrong relative time can be shown to the users. This is because caching plugins generate HTML documents from the PHP files, they will display the time when they generate the static HTML page, and not the correct time when the current user would have opened the page.

WordPress Functions Used

Related Post