Insert Images within Figure Element from Media Uploader
For your functions.php file or a functionality plugin:
function html5_insert_image($html, $id, $caption, $title, $align, $url) {
$html5 = "<figure id='post-$id media-$id' class='align-$align'>";
$html5 .= "<img src='$url' alt='$title' />";
if ($caption) {
$html5 .= "<figcaption>$caption</figcaption>";
}
$html5 .= "</figure>";
return $html5;
}
add_filter( 'image_send_to_editor', 'html5_insert_image', 10, 9 );
It also takes what you enter as a caption and inserts it within the <figure> tag as a <figcaption>. Example inserted code:
<figure id='post-18838 media-18838' class='align-none'>
<img src='http://youresite.com/wp-content/uploads/2012/10/image.png' alt='Title of image'>
<figcaption>Caption for image</figcaption>
</figure>
That’s nice, but it can be improved. :)
function html5_insert_image($html, $id, $caption, $title, $align, $url) { $src = wp_get_attachment_image_src( $id, $size, false ); $html5 = "<figure id='post-$id media-$id' class='align$align'>"; $html5 .= "<img src='$src[0]' alt='$title' width='$src[1]' height='$src[2]' />"; $html5 .= "</figure>"; return $html5; } add_filter( 'image_send_to_editor', 'html5_insert_image', 10, 9 );Note that
$urldoesn’t hold the image’s source URL, but the value of the “Link URL” field from the “Add Media” window. Getting the actual image source URL viawp_get_attachment_image_src()and$idshould be much safer.For my part, I’d also screw the
$captionpart which should be done via theimage_add_caption_shortcodefilter. But the above function could use a statement for optional links on images.Dang, this doesn’t appear to work in WordPress 3.5. Couldn’t understand why no-one had picked up on this snippet not working at first but a quick switch to a localhost running 3.4 shows it worked just fine. Question is: what’s changed / broken?
All the best, Karl
Really digging this little snippet! Just gave it a shot on my latest build and it worked without issue! Thanks for sharing Chris!