Always use 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 );

Leave a Comment