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>.