Quick Tip: Display Timeago For WordPress If Less Than 24 Hours

written by aext on April 14, 2010 in WordPress and Quick Tips with 48 comments

This small code snippet will help you to display the time ago for WordPress post if your post was published less than 24 hours ago. You can find some code published on other blogs that used for displaying the time different from now to the time when the post published like: “minutes ago“, “hours ago“, “days ago“… This code will display only when the different time is less than 24 hours.

The completed code you need is below. Copy it and paste it to the functions.php file and you are ready to go. No more messing needed.

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 ) );
        $display = date(get_option('date_format'), strtotime($date) );

    return $display;

This code will hook into the the_time() function. It will do the filter which modify the return value of the_time() before sending it to the browser screen.

The output:

Published:  5 minutes ago
Published:  12 hours ago


Published:  March 14, 2010 //Depends on your date format setting

Don’t forget to subscribe to our rss feed to receive full code snippets and articles via feed reader or follow us on twitter.