Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jlord
Created September 8, 2012 23:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jlord/3680879 to your computer and use it in GitHub Desktop.
Save jlord/3680879 to your computer and use it in GitHub Desktop.
Separate text from images in a page in Wordpress.
Add the bit in the next box to your Wordpress page loop to separate the images from the text
so you can style and move them all easy peasy.
The standard loop should start out like this:
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
Make sure to get rid of things you don't need, especially this:
<?php the_content(); ?>
The loop ends here:
<?php endwhile; ?>
///////////////////////////////////////////////////// what it does //////////////
<?php
// get the content from the post
$posttext = $post->post_content;
// make a variable for the string you're looking to find in all of the content
$regex = '~<img [^\>]*\ />~';
// find the first things inside of the second thing and put them inside of the third thing
preg_match_all($regex, $posttext, $images);
// redefine posttext as itself minus all the things you found
$posttext = preg_replace($regex, '', $posttext);
// now posttext has no images, and $images is an array of image tags
// have fun, o lord of jellies ?> <!-- this part is from issac -->
<div id="thePostText">
<?php
// now spit out all the text
echo $posttext; ?>
</div>
<div id='thePostImages'>
<?php
// for each image, wrap it in the p tags and spit it out
foreach ( $images[0] as $image ) {
echo '<p class="aPostImage">' . $image . '</p>'; } ?>
</div>
///////////////////////////////////////////// Thank you @izs for helping! ///////////// weeeeee
<?php
$posttext = $post->post_content;
$regex = '~<img [^\>]*\ />~';
preg_match_all($regex, $posttext, $images);
$posttext = preg_replace($regex, '', $posttext); ?>
<div id="thePostText">
<?php echo $posttext; ?>
</div>
<div id='thePostImages'>
<?php foreach ( $images[0] as $image ) {
echo '<p class="aPostImage">' . $image . '</p>'; } ?>
</div>
@harshclimate
Copy link

harshclimate commented Nov 20, 2017

A problem I ran in to with this bit of code is that $posttext removes the paragraph tags completely.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment