April 14, 2014

Extract images and text from post content WordPress

Hey There, Ever had a post with lots of images in it and you wanted text and images displayed separately from the post content?
Well, before a week ago I got exactly same situation where I need to display images from post content on the top and the text under it. It was a blog page of the site and showing excerpt there.
Showing the text only without image wasn’t difficult. I applied this php code and it’s done.

 echo substr(preg_replace('/<img />]+./','',$post->post_content),0,350); 
But extracting the images especially multiple from post content and showing them on the top of the blog entry was a little bit tricky part of this job.
So, what I did to extract images from post content is put this code where I need images to be displayed
 $ptrn = '~<img [^\>]*\ />~';
 // Run preg_match_all to grab all the images and save the results in $imgs
 preg_match_all( $ptrn, $post->post_content, $imgs );
 // Check to see if we have at least 1 image
 $imgs = count($imgs[0]);
 if ( $imgs > 0 ) {
  // Now here you would do whatever you need to do with the images
  // For this example the images are just displayed
  for ( $i=0; $i < $imgs; $i++ ) {
   echo "<li class='img'>".$imgs[0][$i]."</li>";
The Final Result
And it’s all done. I got exactly the same output when I run the code.
If you like this post don’t forget to share or comment.
Follow us for more updates on web technologies.
Enjoy the code !!

Kindle Apps