Stop Wrapping WordPress Images in Paragraphs

WordPress insists on wrapping your img elements in p tags. This function will wrap them in a div instead, which is much more useful.

function agw_wrap_images($content) {
    return preg_replace('/<p[^>]*>\\s*?(<a .*?><img.*?><\\/a>|<img.*?>)?\\s*<\/p>/', '<div class="post-image">$1</div>', $content);
add_filter('the_content', 'agw_wrap_images');

Adam Walter is a front-end developer, lover of WordPress, and Director of Development at Vital in Portsmouth, NH. Read more about me →