Quick WordPress Tip: Style Posts According to Date

Ever wanted to give a post element a different look and feel (or even include/exclude content) based on a post’s publication date? I got asked about this earlier today, and I figured it would be a handy tip to share.

I don’t claim to be a PHP coder, so while it does work, it could be that this can be shortened somewhat. Feel free to use it as a base for making it more efficient, if you’d like (and if you can, I’d love to see what you come up with!).

OK… Somewhere within the Loop, before the area you want to customise, enter the following:

<?php $postdate = the_date('Y-m-d','','',false); ?>

That tells WP to find out the publication date of a post and to assign it to the function, $postdate. You can then call that function later in the post. For example:

<?php if ($postdate < date("2008-12-29")) echo ' class="old"'; ?>

That snippet of code will check to see if the post was published after 29th December, 2008. If not, it will be assigned the “old” class, and you can style that however you like through your stylesheet.

Of course, it’s not limited to CSS styling — you can place whatever you like within the if statement, so you could, say, choose to show full posts after a certain date, and excerpts of posts written earlier.


5 Comments on Quick WordPress Tip: Style Posts According to Date

  1. Nice. I haven’t had a use for this yet, but now that you’ve posted it, I may have to add it to my arsenal for the next redesign. Thanks

    Comment by ReTodd at 5:25 pm, 6th March, 2009

  2. Nice post. Handy stuff to know. Thanks.

    Comment by kelvinwins.com at 5:31 pm, 6th March, 2009

  3. Thanks guys. Yeah, it’s not something that’s likely to be widely needed, but I do think it’s cool that it’s possible to have this kind of functionality in WordPress for the rare occasions that you need to to do slightly more complex stuff.

    Comment by Rob Barrett at 1:32 am, 15th March, 2009

  4. I want to implement this snippet so I can distinguish posts by date originated.

    Comment by Dish Network at 12:17 pm, 12th July, 2009

  5. Dish Network: This will work for that. Just enter the first snippet into the Loop, and $postdate will output the publication date of each post.

    Comment by Rob Barrett at 4:19 pm, 12th July, 2009