I am making a WordPress theme and want to change the default image html. For example if you upload an image using WordPress uploader it generates the following html for your images
<a href="image_url_goes_here" rel="nofollow noreferrer noopener">
<img class="aligncenter size-full wp-image-100" src="your_src"/>
</a>
I want to change it to something like this
<div class="image-container">
<img class="aligncenter size-full wp-image-100" src="your_src"/>
</div>
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
This will do:
<?php
/*
* This filter only works with images, for all kind of media check: media_send_to_editor
* The priority is set to 20 and it takes 8 arguments
*/
add_filter('image_send_to_editor', 'wpse_53577_img_wrapper', 20, 8);
// We are only working with the $html argument, but you can play with all of them
function wpse_53577_img_wrapper($html, $id, $caption, $title, $align, $url, $size, $alt)
{
// If Link URL is set to "File URL" or "Attachment Post URL", the anchor tag gets replaced with the div tag
$new_html = preg_replace("/<a(.*)>(.*)</a>/iU", "<div class="image-container">$2</div>", $html);
// If no replacement was done (Link URL == None), wrap the image tag with the div tag
$html = ($new_html == $html) ? '<div class="image-container">'. $html . '</div>' : $new_html;
return $html;
}
Reference snapshot:

The replacement of the anchor tag is done with a Regular Expression (RegEx), which I’m not versed with… Found it doing this search.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0