Code wrapping empty space in class tags

I have the following code in my functions.php which wraps the text in my WordPress posts in and and leaves the images intact/unwrapped

functions.php

function sr_wrap_content_in_div( $content )
{
$contents = explode("<img", $content);
foreach($contents as $content)
{
    $before_tag = strstr($content, '/>', true); 
    $after_tag = strstr($content, '/>');
    if( $before_tag == '' && $after_tag == '' )
    {
        echo '<div class="content-wrap row"><div class="col-md-10 col-md-push-1">'; // change it later if you need to
        echo $content;
        echo '</div></div>';
    } else if( $after_tag == '/> ' )
    {
        echo '<img';
        echo $before_tag;
        echo '/>';
    } else 
    {
        echo '<img';
        echo $before_tag;
        echo '/>';
        echo '<div class="content-wrap row"><div class="col-md-10 col-md-push-1">'; // change here too.
        echo substr($after_tag, 2);
        echo '</div></div>';
    }
}
}
add_filter( 'the_content', 'sr_wrap_content_in_div' );

output

<div class="content-wrap row">
   <div class="col-md-10 col-md-push-1">
      ... content
   </div>
</div>

The code works, however it wraps empty spaces (in between images, etc) in those classes. This means I cannot apply margin css to .content-wrap because it will create gaps in empty spaces.

Read more here: Code wrapping empty space in class tags

Leave a Reply

Your email address will not be published. Required fields are marked *