How to remove <p> 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 <p> tags from images in WordPress

  1. Clever idea. I use with a HTML5 enabled theme. When a theme reports itself to support HTML5, wordpress output when a caption is present, but when not. So I changed the regexp to make the latter case look like the former, so that all images have the same html. This is my code:

    add_filter(‘the_content’, function ($html) {
    return preg_replace(‘/\s*()?\s*\s*()?\s*/si’, ‘$1$9’, $html);
    }, 100);

    1. Unfortunately, the code in my comment scrambled. Just as well, because it ballae out in special circumstances. I have polished it and made it more robust. I have divided the code of Google Docs:

  2. Hi
    Thanks for the code. Dreamweaver says «invalid mark up» for:
    But the code seems to work.

    1. The code was omitted. «»

      1. sorry, hope this works

  3. You’re a genius, worked like a charm. Thank you!

  4. Hello, Your script solved my problem . Thanks.

  5. Thank you! Just what I was looking for! Pesky image embed was not working in my favor until I found your snippet! Thanks!

  6. Hi,

    Where exactly do I put it in the functions.php. It’s quite a huge file easily breakable.


    1. Hi

      If you’re having difficulties knowing where to put the snippet, consider using it to create a mini plugin of your own.

  7. Great! Thank you very much!

Comments are closed.