wrap div around images

Hi, I’d like to know how to set wordpress to automatically wrap a <div> around any <img> that users insert into the posts (and only those <img>!).
I have a CSS need to style those with a <div> around, because I have to use a pseudo selector ‘:before’ and it won’t work with <img> alone (or at least I can’t).

When the admin or a simple author or editor writes a post, he can insert an image via MEDIA.
Wordpress automatically puts an <img> tag inside the post.
I want WordPress to wrap automatically a <div> around that <img> tag. This <div> will also have a class named “figure” just to stile it with CSS.

Is there a function I can put inside functions.php in order to accomplish this task? (wrapping the div?).

The styling I have to make is too complex to make with just a <img> tag, also if classed, and some users can’t manually insert the required HTML by their own.

Ok. I don’t know. There may be hook that you can use when you insert the image but nothing looks obvious to me. From one standpoint, this would be best case but from another standpoint, not so much. See the ‘meddling’ part below.

You could do this with the save_post filter. You would need to search and replace your images with div wrapped versions of them. I don’t know if I have anything that would do that but I’ll look around if I get the chance. The downside is that the markup would not be in the editor window until at least one save, and the markup would be vulnerable to meddling on the backend. That is, someone could edit your tag on the backend, and you may end up with nested divs or broken divs.

You could do the same thing on post display using the the_content filter. The downside is more processing when the page loads. The upside is that your markup would be harder to break as it wouldn’t show up on the backend at all.

That stackexchange article has a decent start at your filter. Whether that is the right way or not depends on what you want. There is an upside and a downside to adding the markup on insert or save– people can break it later.