PHP Time Comparison in WordPress Themes

Posted on in Programming

ProBlogger Darren Rowse recently posted a question about putting dates on blog posts. A lot of folks were interested in the idea of removing dates from older blog posts, but don't know where to start. This is a useful PHP excercise, so I decided to implement it on my personal blog as a test.

"post_with_date"My personal blog uses a modified version of the Misty Look theme by Sadish Bala. The image on the right shows the normal look for a post on the site. What you see is the title, followed by the date and an author link. This is the typical meta data supplied on 99% of blog posts out there. In fact, you'll find similar information at the bottom of this post.

The trick is to change the theme so that it only displays the date if the post is NEWER than a specific date. For our purposes, we'll assume that any post older than 30 days should not show the date. We'll do this with PHP in the single page theme file (single.php). Here's the original code that printed out the post meta data (I've formatted it a bit to make it more readable):

<p class="post-info">
 <?php the_time('M jS, Y') ?>
 by <?php the_author_posts_link() ?>
 <?php edit_post_link('edit', '', ''); ?>

We need to change that call to the WordPress Template Tag the_time() that always happens and replace it with a time comparison. Here's what the final code looks like:

<p class="post-info">
  $days      = 30;
  $post_time = get_the_time('U');
  $now       = time();

  if ( $now - $post_time < $days * 86400 ) {
    the_time('M jS, Y');
 by <?php the_author_posts_link() ?>
 <?php edit_post_link('edit', '', ''); ?>

What we've done is set the variable $days to the maximum age of posts that display dates. We get the time of the current post as a UNIX timestamp via the WordPress Template Tag get_the_time(). We store the current time (again as a UNIX timestamp) in $now. Finally, we subtract the post time from the current time, and if the difference is less than the number of seconds in $days we print the date. Otherwise, the code does nothing and moves on to the author attribute.

"post without date"As you can see in the image on the left, this post does not contain the date. The post was made on June 3, 2008 well over 30 days from today (July 21, 2008). Whether or not this is a useful thing to do is really a decision best left to the blogger. But, if you were curious, now you know.

As always, if you have any questions or comments, leave them below or send me an email.

My Bookshelf

Reading Now

Other Stuff