
The Art of Date/Time Stamping
- April 18, 2017
- Leave a comment
In WordPress, generally the articles are dated whenever they are published. Sometimes, you might want to display the time of a published article in a different format depending upon your requirements. One of the ways is to show the time stamping, which means how long ago an article has been published. For example, like on Twitter you would see “2 Hours Ago”, “1 Day Ago”, “1 Month Ago”, etc.
There is a function in WordPress named as human_time_diff() which can make the time stamping work for you. This function will return the human readable time difference format as mentioned above. You can use this function in the following manner:
1 |
<?php human_time_diff( $from, $to ); ?> |
It has two parameters:
- $from: (Required) Unix timestamp to start the time difference
- $to: (Optional) Unix timestamp to end the time difference
Note: If the parameter is not set, WordPress time() function will be the default value.
For example, let’s pass the post time using get_the_time() function with a parameter U (which depicts the Unix timestamp format). To get the publish time of a post, from parameter of human_time_diff() and the current_time() will pass with the timestamp parameter which would eventually be passed through the to parameter. The final function would look like below:
1 |
<?php echo human_time_diff(get_the_time('U'), current_time('timestamp')).' Ago'; ?> |
The above function will display the post time in a human readable time difference format like “1 Min Ago”, “1 Hour Ago”, “1 Day Ago”, “1 Week Ago” and so on.
User Comments