How to Show “Time Ago” for Posts in WordPress
In WordPress, displaying how long ago a post was published, like “5 minutes ago” or “3 days ago,” helps readers quickly understand how recent your content is. This article shares an easy-to-use PHP snippet that adds this feature to your WordPress site, perfect for beginners and developers alike.
// Displays the human-readable time elapsed since a post was published
function display_post_time_elapsed($post_id = null) {
if (!function_exists('human_time_diff')) {
return esc_html('Unknown time');
}
$post_time = get_the_time('U', $post_id ?: get_the_ID());
$current_time = current_time('timestamp');
return $post_time ? esc_html(human_time_diff($post_time, $current_time)) : esc_html('Unknown time');
}How It Works
The code calculates the time difference between when a post was published and the current time, using WordPress’s built-in tools. It automatically formats the result into easy-to-read phrases, ensuring correct wording like “1 minute ago” for a single minute or “2 minutes ago” for multiple minutes, and similarly for hours, days, and more.
The snippet is safe to use, with checks to avoid errors if something goes wrong (like an invalid post time), in which case it displays “Unknown time.” It’s also secure, ensuring the output won’t cause issues on your site.
What You’ll See
When you use this code, it shows how long ago a post was published in a simple, easy-to-read way. For example:
- A post published 1 minute ago will show as “1 minute ago.”
- A post from 2 hours ago will show as “2 hours ago.”
- A post from yesterday will show as “1 day ago.”
- A post from two days ago will show as “2 days ago.”
The text automatically uses the right form singular for one (like “1 minute”) and plural for more (like “2 minutes”) – so it always looks natural and clear to your readers. For instance, in a blog list, you might see something like “My Post Title – 4 hours ago.” This is perfect for letting people know how recent your posts, news, or comments are, making your site feel fresh and lively.
To get it working, paste the code into your theme’s functions.php file. Then, in your theme’s template files (like single.php for single posts or archive.php for post lists), add echo display_post_time_elapsed(); to show the time for the current post. If you want to show the time for a specific post, use echo display_post_time_elapsed(123); with the post’s ID (like 123). It’s an easy way to make your WordPress site more inviting and keep readers in the loop!
Written by Milan on 10th July 2025

