HTML tags in WordPress image caption

I’m glad that better support should be added in version 3.4 but for now I’ve fixed the issue by changing the behaviour of image insertion so that it doesn’t use the shortcode.

Here’s what I added to functions.php:

add_filter( 'disable_captions', create_function('$a', 'return true;') );

function image_send_to_editor_2($html, $id, $caption, $title, $align, $url, $size, $alt) {
    if ( !$caption ) {
        return $html;
    } else {
        $width="auto";
        if ( preg_match( '/width="([0-9]+)/', $html, $matches ) ) {
            $width = $matches[1] . 'px';
        }

        $output="<div id="attachment-" . $id . '" class="wp-caption align' . $align . '" style="width: ' . $width . ';">';
        $output .= $html;
        $output .= '<p class="wp-caption-text">' . $caption . '</p>';
        $output .= '</div>';

        return $output;
    }

}

add_filter('image_send_to_editor', 'image_send_to_editor_2', 10, 8);

This works best with the TinyMCE Advanced plugin with its option to stop removing (and adding) <p> and <br /> tags enabled.