How to remove <code><p></code> tags from images in WordPress

Development News

By default WordPress will wrap any images you insert into a post in a paragraph tag. While this isn’t the worst crime semantically speaking it can make life difficult if you want to style those images a certain way. Typically you can target images within a paragraph tag using CSS however you cannot target the paragraph tag itself.

To get around this limitation here’s a snippet for your functions.php:

// img unautop
function img_unautop($pee) {
    $pee = preg_replace('/<p>\\s*?(<a .*?><img.*?><\\/a>|<img.*?>)?\\s*<\\/p>/s', '<div class="figure">$1</div>', $pee);
    return $pee;
}
add_filter( 'the_content', 'img_unautop', 30 );

In the second argument of preg_replace you edit it to wrap the image in any markup you like, in particular if your theme is HTML5 you would replace <div class="figure">$1</div> with <figure>$1</figure>.

43 responses to “How to remove <code><p></code> tags from images in WordPress

  1. Thank you, Robert! I was trying to find a solution to this for the longest time… You’re the man, brother.

  2. I’m having similar problems like some resent posters. I have some content that seems to be the perfect storm that renders my content missing, the_content() returns nothing.

    1. An anchor tag surrounded by a paragraph.
    2. An iFrame
    3. A gallery

    Removing one of the above returns my content again.

    Example from my content blob:
    [code]
    Some text.

    example

    Some more.

    The Puppetman from Ema Ryan Yamazaki on Vimeo.

    [gallery link="file" ids="1, 2, 3"]
    [/code]

    1. Well that didn’t work. Here is the content in my blob.
      http://codepen.io/anon/pen/gyqBm

  3. Great. Thanks!

  4. This is wonderful Robert! Thank you for sharing this snippet.

  5. The regex seems to be catching paragraphs that start with a link, even if it’s not an image, puting these text blocks inside as well. Have you noticed that, or am I crazy? Either way, thanks for the snippet.

  6. For some reason stops working after a random amount of imgs are adde to the post. And when I preview the draft it suppresses imgs and text altogether.
    I’m using wp 351
    Thanks

    1. It’s difficult to say without seeing the post and the generated markup. It will really only work for images that are on their own inside a paragraph tag with no other text.

  7. Thank you thank you thank you thank you!!! I needed this especially for a special print.css in my homemade styling and I’m a novice so this really, really helped! The thing, which indents my paragraphs 0.5 inch to look like APA academic format, was bumping my images over, too. This helped so much; thanks again! – jg –

  8. Awesome stuff man! Cheers!

  9. Amazing!!! Thank you very much!

Comments are closed.