Transfer WordPress Image Captions to HTML5

The html5 is a new web standard, more and more websites using html5 now. The default WordPress theme twentyeleven using html5, but some of the elements still don’t use the html5 code, just like the image and captions uploaded by the users. This article will help you convert the WordPress default image caption elements to html5 code.

How to add images with captions

Many of you might already be aware of how to do this, but let’s cover the basics for those WordPress users who don’t.

To add an image caption, you must first upload an image using the WordPress media uploader. Once you’ve uploaded an image, you should see an input box labeled “Caption,” which is where you’d add your image caption, as shown in the following screenshot.

wordpress image upload
WordPress image caption

To insert the image with a caption into your post, you’d simply click the “Insert into Post” button just like you would with any other image.

The default code of the html4 for each image will display like this:

Here is the image caption

If you use html5, the code should be

Here is the image caption

How to transfer the default code to html5? Here it is: open the functions.php (you can find it in the theme folder), then copy and paste the following php code to the functions.php

add_filter('img_caption_shortcode', 'html5_img_caption_shortcode', 1, 3 );
function html5_img_caption_shortcode($string, $attr, $content = null) {
    extract(shortcode_atts(array(
        'id'    => '',
        'align' => 'alignnone',
        'width' => '',
        'caption' => ''
    ), $attr)
    );
    if ( 1 > (int) $width || empty($caption) )
        return $content;
 
    $width_style= ' style="width: ' . $width . 'px"';
    if ( $id ) $id = 'id="' . esc_attr($id) . '" ';
 
    return '
' . do_shortcode( $content ) . '
' . $caption . '
'. '
'; }

That’s it, and it is easy to use.