I am trying to add a bit of html markup before and after a media file (image with a link to it's full size) in wordpress.

Anyone know a simple way to do this without having to use a plugin?

Here is the markup I want to have before the image if it does use the "link to: Media file" option.

 <div class="ImageWrapper">
 <div class="ImageOverlayHBlog"></div>

Nothing too special but seems to be giving me a headache on how to get it to show before the images that have links to larger version.

Any help or guidance would be much appreciated!

1 Answer 1


WordPress has a filter image_send_to_editor which lets you modify the html that is generated by the media editor. Usage:

add_filter ('image_send_to_editor', 'wpse264886_filter_image', 10, 8);
function wpse264886_filter_image ($html, $id, $caption, $title, $align, $url, $size, $alt) {
  $html = '<span> ... </span>' . $html;
  return $html;

This will insert the spans always, however, not only when there is a link around the image. If you want the latter, you'd have to filter the content by doing a search and replace, finding all links on images and then insert the html. I'm not very good with regex and haven't been able to test it, but it would be something like this:

add_filter ('the_content', 'wpse264886_content_insert_html', 10, 1);
function wpse264886_content_insert_html ($content) {
  $html = '<div> ... </div>'
  $content = preg_replace('/(<a.*?)><img/', '$1>' . $html . '<img', $content);
  return $content;
  • Hi cjbj! Thanks for this! The second code seems to be what I'm looking for but how do I add in something after the image as well? I'm trying to figure it out but I'm sure you know off the top of your head. Thanks again for the help! =D
    – Ponte
    Apr 25, 2017 at 19:09
  • That would make for an even more complicated regex, with a second wildcard. Quick guess: '/(<a.*?)><(img.*?)/', '$1>' . $html1 . '<$2>' . $html2, $content. If it doesn't work, ask at Stack Overflow.
    – cjbj
    Apr 25, 2017 at 19:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.