[FIX] WordPress 3.0 Invalid HTML5 Gallery Code

WordPress 3.0 generated the following code for a gallery in one of my posts —

<!– see gallery_shortcode() in wp-includes/media.php –>
<div id=’gallery-1′ class=’gallery galleryid-1512′>
<dl class=’gallery-item’>
<dt class=’gallery-icon’>
<!– Image and link here –>
</dt>
</dl>
<dl class=’gallery-item’>
<dt class=’gallery-icon’>
<!– Image and link here –>
</dt>
</dl>
<dl class=’gallery-item’>
<dt class=’gallery-icon’>
<!– Image and link here –>
</dt>
</dl>
<br style=”clear: both” />
</div>

Validating the page produced the following errors —

…and the validator quite rightly states, “element dl: Zero or more groups each consisting of one or more dt elements followed by one or more dd elements.”

If you go through explanation of the dl tag in the HTML5 working draft, you’ll see that the dl tag must contain a dd child element (the actual definition) if it contains a dt child element (the definition term).

The dl element represents an association list consisting of zero or more name-value groups (a description list). Each group must consist of one or more names (dt elements) followed by one or more values (dd elements)

WordPress does not generate the dd element if a caption is not specified.

Personally, I feel using definition lists for galleries is inappropriate. WordPress also allows galleries to be displayed using tags other than dl, dt and dd. You’ll find an example at the bottom of this page.

To generate valid HTML5 code for this website, I’ve added the following code to functions.php in my theme —

function html5_gallery($content)
{
//remove space between [ and gallery in the following line
return str_replace(‘[ gallery’, ‘[ gallery itemtag=”div” icontag=”span” captiontag=”p”‘, $content);
}
add_filter(‘the_content’, ‘html5_gallery’);

Galleries are now displayed using div, span and p tags. It’s slightly inefficient since I’m essentially doing a “find and replace” for the gallery shortcode, but for me, it’s the best way to deal with the problem. You can read more about using add_filter here.

If you have any suggestions for a better workaround (other than modifying wp-includes/media.php :P ), please leave a comment!  :cheers: