Always use <figure> for post images

The default behavior when it comes to full-width images in posts is this:

  • If you insert an image alone, this HTML structure is produced: <p><img/></p>
  • If you insert an image with a caption, the HTML structure is produced: <figure><img/><figcaption/></figure>

For the sake of styling (I want to have larger margin around images compared to standard paragraphs), I’d like to get <figure> in both cases, not just when there is a caption. How to do it?

Edit: one thing I noticed is that the behavior changes as soon as Visual and Text tabs are switched in the editor, i.e., even before previewing or saving the post. Maybe the correct solution would be to somehow force WordPress editor to always use the shortcode no matter what.

Solutions Collecting From Web of "Always use <figure> for post images"

You can try the image_send_to_editor filter:

/**
 * Wrap the inserted image html with <figure> 
 * if the theme supports html5 and the current image has no caption:
 */

add_filter( 'image_send_to_editor', 
    function( $html, $id, $caption, $title, $align, $url, $size, $alt ) 
    {
        if( current_theme_supports( 'html5' )  && ! $caption )
            $html = sprintf( '<figure>%s</figure>', $html ); // Modify to your needs!

        return $html;
    }
, 10, 8 );

where you can modify the html of the image when it’s inserted into the editor.

I added the check for current_theme_supports( 'html5' ) in the above filter, to check if you have something like:

add_theme_support( 'html5', array( ... ) );

in your theme. But you might not want to have this filter callback dependent on your current theme, so you can remove it if you want.

You could also try out the get_image_tag filter.

Update: Here’s the useful unautop function from @bueltge’s comment (for better readability):

// unautop for images     
function fb_unautop_4_img( $content )
{ 
    $content = preg_replace( 
        '/<p>\\s*?(<a rel=\"attachment.*?><img.*?><\\/a>|<img.*?>)?\\s*<\\/p>/s', 
        '<figure>$1</figure>', 
        $content 
    ); 
    return $content; 
} 
add_filter( 'the_content', 'fb_unautop_4_img', 99 );