WordPress: using the HTML5 time element

WordPress: using the HTML5 time element

How to use the HTML5 time element in WordPress.

HTML5 introduces a brand new set of elements that can be used in our WordPress themes. Among them, the time element is used to associate dates and times to an article element (if it's present as ancestor) or to the whole document. In this article we'll see how to use this element effectively on WordPress.

The time element is defined as follows by the HTML5 specifications:

The time element represents its contents, along with a machine-readable form of those contents in the datetime attribute. The kind of content is limited to various kinds of dates, times, time-zone offsets, and durations, as described below.

The datetime attribute may be present. If present, its value must be a representation of the element's contents in a machine-readable format.

A time element that does not have a datetime content attribute must not have any element descendants.

Here's an example of the time element:

<!DOCTYPE html>
<html>
<head>
<title>time</title>
<meta charset="utf-8" />
</head>
<body>
<article>
	<!--content-->
	<time datetime="2012-06-10">June 10, 2012</time>
</article>
</body>
</html>

WordPress already supports a wide variety of date and time formats that can be used with the datetime attribute (see Formatting Date and Time on the WordPress documentation).

Here's a sample Loop that makes use of the time element together with the WordPress date and time functions:

<?php

   while(have_posts()):
       the_post();
   ?>
   
   <article id="<?php the_ID();?>">
     <header>
   		<time datetime="<?php the_date('Y-m-d');?>"><?php the_time('F j, Y');?></time>
   		<h2 class="entry-title"><a href="<?php the_permalink();?>" rel="bookmark"><?php the_title();?></a></h2>
   	 </header>
   		<div class="entry-content"><?php the_excerpt();?></div>
   </article>
   
<?php
  endwhile;
?>

The result is shown below:

[caption id="attachment_1921" align="aligncenter" width="430" caption="The HTML5 time element displayed in a WordPress theme"]The HTML5 time element displayed in a WordPress theme[/caption]

The pubdate attribute

Using the pubdate attribute often results in a validation error. The W3C validator simply says that this attribute is not allowed to appear at a certain point. Unfortunately, the HTML5 specifications lack of useful examples for this problem. Some authors report that the problem is due to the date format chosen for the datetime attribute, but I still can't confirm this information.