Displaying “time ago” helps in certain ways, when you blog about any news. It give an impression to your WordPress blog users, that you have broken the news bit earlier. So, let come to the point – how to make it happen. The time ago function in WordPress is called by the function human_time_diff and here I am gonna using the same function to display “3 days ago” for an example on your WordPress Title.
Display “time ago” before the post title
Go to Single.php and search for for an example you may find this as
<h1 class="title"><?php the_title(); ?></h1>
Place the code you find after the php title tag
Posted <?php echo human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ago'; ?> - <?php the_time('F j, Y'); ?>
Now after adding it will look like this
Posted <?php echo human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ago'; ?> - <?php the_time('F j, Y'); ?> <h1 class="title"><?php the_title(); ?></h1>
Display “time ago” after the title of your post
If you want to display “time ago” after the title of your post just add this piece of code on the single.php
Search for the_time
function and place this code along with that
Posted <?php echo human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ago'; ?>
Finally it will look like this
Posted <?php echo human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ago'; ?> <?php the_time($GLOBALS['date']); ?>
The $GLOBALS function varies among different templates, so its just an example to illustrate.
Display “time ago” only if the post is less than 24 hours after published
Thanks to Lam for this piece of code. Go to functions.php and paste this below code, thats it.
add_filter('the_time', 'timeago'); function timeago() { global $post; $date = $post->post_date; $time = get_post_time('G', true, $post); $time_diff = time() - $time; if ( $time_diff > 0 && $time_diff < 24*60*60 ) $display = sprintf( __('%s ago'), human_time_diff( $time ) ); else $display = date(get_option('date_format'), strtotime($date) ); return $display; }
Still having doubts? Drop in your comments.