“Human readable” date

Here’s a short code snippet you can use if you want your date to be displayed as “Today”, “Yesterday” or “X days ago”. To accomplish this, simply add a filter to the_date.

In my example it shows “X days ago” if it less than 7 days old. Short and sweet!

function mytheme_the_date( $date ) {
$time = strtotime( $date );
$difference = time() - $time;
$days_ago = (int)( $difference / 60 / 60 / 24 );

if ( date( 'Y-m-d' ) === date( 'Y-m-d', $time ) )
   return __( 'Today' );
elseif ( date( 'Y-m-d', strtotime('-1 day') ) === date( 'Y-m-d', $time ) )
   return __( 'Yesterday' );
elseif ( $days_ago < 7 )
   return sprintf( __( '%d days ago' ), $days_ago );

return $date;
}
add_filter( 'the_date', 'mytheme_the_date' );

Happy coding!

About

Web Developer @ Oakwood Creative - www.oakwood.se

Tagged with: , ,
Posted in Beginner

Leave a comment

About

WordPress Quick Tips is a blog supplying great tips about WordPress.

We hope to create a great knowledge resource for WordPress developers as well as serving a reminder for all the forgetful ones.

The blog is created and run by Vincent of Oakwood Creative

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 121 other subscribers