Sep 16, 2012

The time in WordPress and how to make it more readable: the classic "X days ago"

Filled under:

The time in WordPress and how to make it more readable: the classic "X days ago"
Lately more and more I see a beautiful way to express the creation date of a post: "X days ago" or "X minutes ago '. I think that besides being more readable displays a nearest time reference for the reader, that at a glance you can assess whether the site has been updated today.

WordPress offers a very user-friendly feature: human_time_diff ($ from, $ to) . The first parameter, $ from , is the earliest date and the second, $ to , is the closest date to today.WordPress calculates the time difference and directly returns a string style 'X days' or' X minutes. " Practically not have to do anything except that these dates must be in Unix format.

To do so, the parameter $ from is the date of creation of the post and the $ to be the current date. The Codex is well explained:

echo human_time_diff( get_the_time('U') , current_time('timestamp') );

get_the_time ('U') gets the date of creation of the post (we will be inside the Loop to run) in Unix format and current_time ('timestamp') the current date in Unix format also. As we said, this statement returns a string of type 'makes X days / minutes'.

Well, this is not bad but do it right, either. For all dates on our website thus leaving the filter will use the_time if our templates we are using the function the_time () . If we are showing the dates by using the get_the_time () , use the filter get_the_time :

$time = human_time_diff( get_the_time('U') , current_time('timestamp') );
echo sprintf( __( 'hace %s', 'dominio' ), $time );

Thus, in all of our posts appear on the far more readable format.

0 comments:

Post a Comment