X

How to Separate Images from Text in WordPress

Snippets by IsItWP

Wondering how to separate images from text in WordPress? This snippet pulls out all your images in your post and puts it in a separate div.

Instructions:

All you have to do is add this code to your theme’s single.php file:


<div class="content-text">
  <h2><?php the_title(); ?></h2>
  <?php
  ob_start();
  the_content('Read the full post',true);
  $postOutput = preg_replace('/<img[^>]+./','', ob_get_contents());
  ob_end_clean();
  echo $postOutput;
  ?>
</div>
<div class="content-img">
  <?php
  preg_match_all("/(<img [^>]*>)/",get_the_content(),$matches,PREG_PATTERN_ORDER);
  for( $i=0; isset($matches[1]) && $i < count($matches[1]); $i++ ) {
    echo $beforeEachImage . $matches[1][$i] . $afterEachImage;}?>
</div>

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: Best WordPress Page Builders (Compared) and how to properly upgrade WordPress.

Comments   Leave a Reply

  1. Alexandre Glenet October 25, 2019 at 9:28 am

    Hello thank you. The problem is that the images are no longer clickable. Do you have a solution for them to be? thank you.

    1. Sadly, this snippet may not support image links.

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!