Remove p tags on images in WordPress posts

I have a WordPress site which posts have images and text within it. I want to remove the <p> tag on the images only.

html:

Read More
    <div class="col-md-12 ">
        <?php the_content(); ?>
    </div>  

This puts each piece into a <p> tag (images and text)

EDIT – what I attempted

html

<?php
        preg_match_all('/(<img [^>]*>)/', get_the_content(), $images);
        for( $i=0; isset($images[1]) && $i < count($images[1]); $i++ ) {
        echo $images[1][$i];
        }
?>  

was able to pull the images out but that’s it

Related posts

1 comment

  1. No need to reinvent the wheel, CSS Tricks have a great example that is used by quite a few themes and devs:

    function filter_ptags_on_images($content){
       return preg_replace('/<p>s*(<a .*>)?s*(<img .* />)s*(</a>)?s*</p>/iU', '123', $content);
    }
    
    add_filter('the_content', 'filter_ptags_on_images');
    

    Just apply this filter in your themes /functions.php

Comments are closed.