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.
Hello thank you. The problem is that the images are no longer clickable. Do you have a solution for them to be? thank you.
Sadly, this snippet may not support image links.