How Do I Customize the HTML Markup of Images Inserted into WordPress Posts?

I have searched high and low for a solution to this. I want to change the markup of an uploaded image in WordPress from this:

<div id="attachment_906" style="width: 590px" class="wp-caption aligncenter">
    <img class="size-full wp-image-906  " title="Image Alignment 580x300" alt="Image Alignment 580x300" src="http://localhost/sandbox/wp-content/uploads/2013/03/image-alignment-580x300.jpg" width="580" height="300">
    <p class="wp-caption-text">Look at 580×300 getting some <a title="Image Settings" href="http://en.support.wordpress.com/images/image-settings/">caption</a> love.</p>
</div>

To something more like this:

Read More
<figure class="center">
    <img class="gallery-img" src="http://lorempixel.com/300/500/">
    <figcaption>
        <span>A slightly longer caption for the image, which is significantly smaller than the last one. pretty neat!</span>
    </figcaption>
</figure>

I understand that much of the markup in the original post needs to stay, but is there any way to customize any of this? Even if I could get the same basic structure (a wrapper, the image, a caption wrapper, the caption) I could take it from there with CSS.

Since I’m developing a theme, I need the options to work with the native WordPress tools. If that isn’t the case, I can’t work with it.

I had hoped that there would simply be a filter or action that I could apply to do this, but I have had no luck in finding such a thing.

Thanks in advance!

Related posts

1 comment

  1. You need to use the image_send_to_editor filter. https://developer.wordpress.org/reference/hooks/image_send_to_editor/

    That could look something like this in any one of your active theme or plugin’s php files (like functions.php);

    function filter_image_send_to_editor($content) {
      $content .= '<figure class="center">(Generate your markup here)</figure>';
    
      return $content;
    }
    add_filter('image_send_to_editor', 'filter_image_send_to_editor');
    

    You’ll have to write your own code inside that function, of course.

Comments are closed.