Are you looking for a way to convert a date/timestamp to “time ago” timestamp for posts? Displaying an exact date on your posts is great, but why not change things up just a little and display “1 Hour Ago”, “2 Hours Ago”, “1 Day Ago”, “2 Days Ago”, “1 Week Ago”, etc. This snippet lets you create a “time ago” timestamp like social media websites use.
Instructions:
Add this code to your theme’s functions.php file or in a site-specific plugin:
function time_ago( $type = 'post' ) { $d = 'comment' == $type ? 'get_comment_time' : 'get_post_time'; return human_time_diff($d('U'), current_time('timestamp')) . " " . __('ago'); }
Then just add this snippet to your single.php file, index.php file, or any other template within The Loop. For example, you can replace the the_time()
function with time_ago()
.
<?php echo time_ago(); ?>
For a more advanced version, this snippet will create a timestamp that will change to the date after a certain time. Then just add this snippet to your single.php file, index.php file, or any other template within The Loop. Edit line 9 to use the number of seconds you want before the timestamp will change to the date.
<?php # For posts & pages # echo human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ago'; # For comments # echo human_time_diff(get_comment_time('U'), current_time('timestamp')) . ' ago'; // Change to the date after a certain time $time_difference = current_time('timestamp') - get_the_time('U'); if($time_difference < 86400) { //here goes the code from one of the sample above } else { the_time(); }; ?>
Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly add code snippets in WordPress, so you don’t accidentally break your site.
If you liked this code snippet, please consider checking out our other articles on the site like: 6 best Stripe payment plugins for WordPress and how to create a review site in WordPress.
maybe you should start thinking about internationalising your snippets, we’re living in the 21st century after all…
Lots of things I would like to add to the site, however only so much time in a day. This is a good idea though, thanks.