WordPress Code Snippets

A fresh mix of code snippets and tutorials

Display user-friendly dates and times

22

Normally WordPress displays dates using boring old numbers. How much more fun would it be to display dates and times using human-readable language to make them all user-friendly and swell.

To make it happen, just add the following snippet to your theme’s functions.php file:

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;
}
add_filter('the_time', 'timeago');

Once in place, you can see it in action by using the_time() template tag as prescribed.

Related Posts

Learn more

WordPress Themes In Depth


Show Support

Like our new Facebook Page to show support!