How to use HTML5 figure and caption elements in WordPress

To use HTML5 <figure> and <caption> elements in WordPress, you can use the img_caption_shortcode filter hook in your theme’s functions.php file. This hook allows you to customize the output of the shortcode, which is used to add captions to images in WordPress.

Here’s an example of how you can use this hook to output the <figure> and <caption> elements instead of the default <div> element:

// Use HTML5 figure and caption elements
// More snippets at wpunplugged.com 

add_filter( 'img_caption_shortcode', 'custom_caption_shortcode', 10, 3 );
function custom_caption_shortcode( $empty, $attr, $content ) {
    // Extract the attributes
    extract( shortcode_atts( array(
        'id'      => '',
        'align'   => 'alignnone',
        'width'   => '',
        'caption' => '',
        'class'   => '',
    ), $attr ) );
 
    // Build the figure and caption elements
    $output  = '<figure id="' . esc_attr( $id ) . '" class="' . esc_attr( $align ) . ' ' . esc_attr( $class ) . '">';
    $output .= do_shortcode( $content );
    $output .= '<figcaption>' . esc_html( $caption ) . '</figcaption>';
    $output .= '</figure>';
 
    // Return the modified output
    return $output;
}

This code will replace the default <div> element with the <figure> and <caption> elements when the shortcode is used in WordPress. You can then use CSS to style these elements as needed.

Keep in mind that the img_caption_shortcode filter hook may not be the only way to use the <figure> and <caption> elements in WordPress, depending on your specific requirements and use case. If you want to use these elements in other contexts, you may need to use a different approach.

Share this post

You might also like...

Comment

Your email address will not be published. Required fields are marked *