I need to post this because as someone who never uses regular expressions, I scoured the net for hours trying to get some answers and knowledge about how to do what should have been something simple: make WordPress auto-wrap images in div tags, not p tags.
Context
It’s not valid to insert image tags into your content without some kind of block element wrapped around them so if WordPress sees you’ve failed to do that, it wraps your images in paragraph tags for you. The problem is, styles on the <p>
tags mess with styles on the images.
Now normally this really isn’t an issue because I can simply wrap my images in <div>
tags as I write the content, but I’m developing a theme with special image styles that not all browsers support on images. So I absolutely need to have divs around the images and I can’t control what the end user does when s/he creates the content.
So…
Remove The P Tags From Images
Here’s what I found. There were many instances of this solution which removed the <p>
tags from around images, even images wrapped in anchor tags. I believe the original instance for this version was posted by a guy named Leif in the comments of Chris Coyer’s post, Remove Paragraph Tags from Around Images. His version accurately accounts for images wrapped in anchor tags.
function filter_ptags_on_images($content) { return preg_replace('/<p>\\s*?(<a .*?><img .*?/>< \\/a>|<img .*?/>)?\\s*< \\/p>/s', '\1', $content); } add_filter('the_content', 'filter_ptags_on_images');
Replace The P Tages With Div Tags
However, I needed a solution that actually replaced the <p>
tags with <div>
tags… and a class I could target. Funny no one anywhere had a solution I could simply copy and paste. I saw a number of people asking how to do this, but in each case, some other solution was offered that never truly satisfied the request. I did manage to find enough information to piece together something that did the trick and this is what I devised.
function filter_ptags_on_images($content) { return preg_replace('/<p[^>]*>\\s*?(<a .*?><img.*?><\\/a>|<img.*?>)?\\s*<\/p>/', '<div class="radius_fix">$1</div>', $content); } add_filter('the_content', 'filter_ptags_on_images');
Notice I added a class name to the opening div tag. This accurately found all my images wrapped in paragraphs and changed them to divs with the class. No guarantees that there isn’t some bizarre scenario where this won’t work. I do not know REGEX at all so any helpful comments will be appreciated.