How to: Display your latest Twitter-like “time ago” on your WordPress blog

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.
Twitter have a really cool built-in function that display time from now, like “3 days ago” or “more than a month ago”. Doing so with WordPress is not hard using some PHP. Here is a function to do so.

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 ) );
    else
        $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

Or

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

The first thing to do is to create the function. To do so, paste the following into your functions.php file:

<pre>function time_ago( $type = 'post' ) {
	$d = 'comment' == $type ? 'get_comment_time' : 'get_post_time';
	return human_time_diff($d('U'), current_time('timestamp')) . " " . __('ago');
}

Once done, you can use the function in your theme files:

<pre><?php echo time_ago(); ?>

source:http://www.wprecipes.com/how-to-display-twitter-like-time-ago-on-your-wordpress-blog

Web Hosting

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *

*