treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Insert Images within Figure Element from Media Uploader

Last updated on:

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>
View Comments

Comments

  1. 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 $url doesn’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 via wp_get_attachment_image_src() and $id should be much safer.

    For my part, I’d also screw the $caption part which should be done via the image_add_caption_shortcode filter. But the above function could use a statement for optional links on images.

  2. Karl
    Permalink to comment#

    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

  3. Really digging this little snippet! Just gave it a shot on my latest build and it worked without issue! Thanks for sharing Chris!

Leave a Comment

Use markdown or basic HTML and be nice.