Theming a Node Post Date With Drupal 7


In this article I will show you how to theme a post date in Drupal 7. The goal is to take a boring date printed inline and theme it so it stands out as a design element. I covered this a while back for Drupal 6 so I thought this would be a nice update for doing this with Drupal 7.

An example of a themed date in parts

An example of a themed date in parts

First Steps

The first step is to enable "Display author and date information" on your content type edit page at:

/admin/structure/types/manage/[your_custom_content_type]

…as shown below:

Get the Data

We can now go retrieve this data in the node.tpl.php file and alter the theming of the post date. Ideally this will be for a custom node template and not the main node.tpl.php file. In my case, I have a content type called blog and I only want the post date to look this way for blog posts. I take node.tpl.php (located in my theme folder) and copy and rename it to node--blog.tpl.php. Note the "double dashes", that's new in Drupal 7.

Find the Code to Replace

Now looking in my new node--blog.tpl.php file, I see the PHP code I am after that I will then alter:

<?php if ($display_submitted): ?>
  <div class="submitted"><?php print $date; ?> -- <?php print $name; ?></div>
<?php endif; ?>

I want to replace this with some custom PHP code essentially breaking the date up into parts, and getting rid of the author name (though you could easily add this back in and theme it).</p>

Code it

Here is our new code:

<?php if ($display_submitted): ?>
  <div class="date-in-parts">
    <span class="day"><?php  echo date("j", $node->created); ?></span>
    <span class="month"><?php echo date("M", $node->created); ?></span>
    <span class="year"><?php echo date("Y", $node->created); ?></span>
  </div><!--//date-in-parts -->
<?php endif; ?>

Theme it

As you can see, we now have broken the date up into parts which is highly themable. You can make it round, square, or whatever you want with some CSS3 goodness. Note: you will also want to refer to the PHP date manual to get the desired date format.

</p>

Resources

Tags