Display The Post Date In WordPress

If you are building a WordPress theme then there will a time when you want to display the date for the current post, luckily for you this is very easy with a WordPress function the_date().

The the_date function will return the date of the post or the set of posts if published on the same date. This function has the option of passing in 4 parameters.

  • The format.
  • HTML to place before the date
  • HTML to place after the date
  • Boolean if to echo the date or not.
<?php the_date( $format, $before, $after, $echo ); ?>

Get The Date Function

Calendar
If you are using the WordPress loop to display your posts then you should be using the get_the_date() function. The difference is get_the_date() will always return the date of the current post.

This doesn't have any parameters so using it is very simple.

<span class="entry-date"><?php echo get_the_date(); ?></span>

Human Readable Difference Date

If you want to display the date like Twitter does so 2 days ago, 1 day ago, WordPress has a function where you can display the difference of 2 dates.

By using the human_time_diff() function.

<?php human_time_diff( $from, $to ); ?>

If you don't supply it with a to date it will default to now.

To display 2 days ago use the following snippet.

<?php echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago'; ?>

Keep updated with the latest tutorials and snippets.

Join me on Twitter | G+ | Facebook

Comment