0

HTML5 provides a time element, and a lot of modern sites are using the time element for their content post dates.

How can I override a node's post date theming, so I can change the rendering from a div element to a time element?

Currently, the markup looks like:

<div class="field__item even">2015-01-17</div>

I want it to render it as:

<time datetime="2015-01-17T12:00">2015-01-17</time>

I would like to handle this in my theme, since I have an Omega 4 subtheme I use as a base theme for client sites and want it to handle the functionality.

2
  • is this on a node page or views? Mar 14, 2015 at 7:18
  • At first, a node page.
    – vintorg
    Mar 14, 2015 at 12:56

1 Answer 1

1

I'm using Display Suite, which takes over the node's created timestamp and turns it into a field named post_date. Therefore, I overrode the field.tpl.php file and named it field--post-date.tpl.php, and added the time element to the markup:

<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;</div>
  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><time datetime="<?php print $datetime; ?>"><?php print render($item); ?></time></div>
    <?php endforeach; ?>
  </div>
</div>

To get the $datetime variable, I added the following code to theme_preprocess_field():

function mytheme_preprocess_field(&$vars) {
    // check for Display Suite fields.
    if ($vars['element']['#field_type'] != 'ds') {
        return;
    }
    switch ($vars['element']['#field_name']) {
        case 'post_date':
            if ($vars['element']['#entity_type'] != 'node') {
                break;
            }
            $node = $vars['element']['#object'];
            $vars['datetime'] = date_iso8601($node->created);
        break;
    }
}

I'm just handling nodes, and a node always has one created time. The loop in the tpl file can probably be removed, since there will always be one value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.