Replace Hardcoded WordPress Caption Shortcode with HTML5

Modernize WordPress image captions by replacing legacy shortcode output with semantic HTML5.

Tue Oct 31 2023
— words · — minutes

Overview

Modernize WordPress image captions by replacing legacy shortcode output with semantic HTML5.

Originally published on Jang Keyte's Blog.

This article covers Replace Hardcoded WordPress Caption Shortcode with HTML5 — practical notes from real-world web development experience.

Code Examples

add_filter('img_caption_shortcode', 'jangkeyte_img_caption_shortcode_filter',10,3);
/**
 * Filter to replace the [caption] shortcode text with HTML5 compliant code
 *
 * @return text HTML content describing embedded figure
 **/
if (! function_exists('jangkeyte_img_caption_shortcode_filter')) {
    function jangkeyte_img_caption_shortcode_filter($val, $attr, $content = null)
    {
        extract(shortcode_atts(array(
            'id'    => '',
            'align' => '',
            'width' => '',
            'caption' => ''
        ), $attr));

        if ( 1 > (int) $width || empty($caption) )
            return $val;

        $capid = '';
        if ( $id ) {
            $id = esc_attr($id);
            $capid = 'id="figcaption_'. $id . '" ';
            $id = 'id="' . $id . '" aria-labelledby="figcaption_' . $id . '" ';
        }

        return '<figure ' . $id . 'class="wp-caption ' . esc_attr($align) . '" >' . do_shortcode( $content ) . '<figcaption ' . $capid . 'class="wp-caption-text text-center">' . $caption . '</figcaption></figure>';
    }
}
.wp-caption {
/* Force the box to be 100% */
width: 100% !important;
}

#content .wp-caption a img {
/* Scale down if too big */
max-width: 99.03225806%; /* 614/620 */
height: auto;
}

Read More

For the full Vietnamese version, switch language using the VI | EN toggle above, or visit the original post.


Thanks for reading!

Replace Hardcoded WordPress Caption Shortcode with HTML5

Tue Oct 31 2023
— words · — minutes