calendar

Display a “Pretty” Post Date

Posted

On services like Twitter and Facebook you’ll see content that was posted “posted X minutes ago” or “posted X days ago”. I like that. I think it’s bit more personalized than simply using the long form date (e.g. December 27th, 2012).

On my site I now display the post dates as a human time diff (aka, a human readable format) if the post is less than a month old. If it’s older than I month, I use the standard date format selected inside the WordPress dashboard under “Settings > General : Date Format” (in my case Month Day, Year).

The Code Snippet

if ( ! function_exists( 'example_posted_on' ) ) :
/**
 * Prints HTML with meta information for the current post-date/time and author.
 *
 * @since Example 1.0
 */
function example_posted_on() {
	$post_date = the_date( 'Y-m-d','','', false );
	$month_ago = date( "Y-m-d", mktime(0,0,0,date("m")-1, date("d"), date("Y")) );
	if ( $post_date > $month_ago ) {
		$post_date = sprintf( __( '%1$s ago', 'example' ), human_time_diff( get_the_time('U'), current_time('timestamp') ) );
	} else {
		$post_date = get_the_date();
	}
	printf( __( 'Posted <time class="entry-date" datetime="%1$s" pubdate>%2$s</time><span class="byline"> by <span class="author vcard">%3$s</span></span>', 'example' ),
		esc_attr( get_the_date( 'c' ) ),
		esc_html( $post_date ),
		esc_html( get_the_author() )
	);
}
endif;

Explanation

Use a Function

Instead of adding this code to each template where I need to display the date, I’ve wrapped it in the function “example_posted_on” so I can reuse and easily update it if needed. Whenever I need to call the date, I just use example_posted_on().

Since this is used in a theme of mine, I’ve wrapped it in a “if ( ! function_exists( ‘example_posted_on’ ) ) :” check so someone can easily override it from a child theme if they need to.

Compare the Timestamps

To check if the date of the post is older than a month, I generate a timestamp to compare with the one from the post:

$month_ago = date( "Y-m-d", mktime(0,0,0,date("m")-1, date("d"), date("Y")) );

You could easily change this to be to any time period you want and compare those timestamps instead.

Make Sure it is Translatable

If you’re wondering why the strings are wrapped in “sprintf” and “printf”, that’s so everything can be translated if someone wants to localize the theme for a different language. Make sure to change the textdomain “example” to whatever you’ve defined as the textdomain in your theme.

Be Careful of Caching

If your site makes use of heavy caching (W3C Total Cache, and/or a good CDN) your post “day” may get stuck for a while. If it’s included as part of a publicly released theme you may want to give users an option to turn it off and use the regular date instead.

Another option (in that case), would be to use javascript to look for the post date, and convert it to a human readable format on front end instead- but that’s probably fodder for another post.

About Devin

I'm a WordPress developer based in Austin, Texas. Follow my projects on GitHub, or more general WordPress ramblings as @devinsays on twitter.

8 thoughts on “Display a “Pretty” Post Date

  1. Harish wrote:

    Thanks for sharing Devin. Regarding the cache issue, can we not create a transient to save the details and if its old to create a new one that expires every 24 hours?

    • Devin wrote:

      Caching plugins and CDNs work by loading a static version of the page. When a user requests a page that hasn’t yet been cached, WordPress builds out the HTML, which is then saved as a static file for subsequent users to view. This reduces load on the server because each of those subsequent visitors doesn’t need WordPress to load in order to view the page.

      Generally that static page will expire every X number of hours (as you define), or when a defined event occurs (i.e. post updated, new comment approved).

      So a transient wouldn’t be any help in this case. What you’d need is for your cache to expire every 24 hours (or less).

      • Harish wrote:

        Thanks Devin for the explanation. I am learning about Transient so was just curious if it could be applied.

  2. Satrya wrote:

    Hi Devin,
    What is the difference between printf and spintf ?

  3. Martin wrote:

    You should note that function the_date(); is depreciated since WordPress 3.0.

    I got this function to work using $post_date = get_the_date('Y-m-d'); instead.

    • Devin wrote:

      I don’t see a note about it being deprecated in the source- but get_the_date does look more robust. Thanks for letting me know.

      • Martin wrote:

        My bad, I just did a quick scan of the Special note on the codex. I mean to say, get_the_date(); is preferred in some cases (not depreciated!).

        With that in mind, I could only get your function to work by changing to get_the_date(); instead.

        Cheers!

  4. Dean wrote:

    Hey Devin,

    this thing is great. Now I’ve one question to this one: If I want to change get_author to the_author_posts_link to get him linked the link+author will be shown before this message. How can I use the linked author on this thing?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>