The problem. Using custom fields to display images associated with your post is definitely a great idea, but many WordPress users would like a solution for retrieving images embedded in the post’s content itself.
The solution. As far as we know, there’s no plug-in to do that. Happily, the following loop will do the job: it searches for images in post content and displays them on the screen.
- Paste the following code anywhere in your theme.
01<?phpif(have_posts()) : ?>02<?phpwhile(have_posts()) : the_post(); ?>0304<?php05$szPostContent=$post->post_content;06$szSearchPattern='~<img [^\>]*\ />~';0708// Run preg_match_all to grab all the images and save the results in $aPics09preg_match_all($szSearchPattern,$szPostContent,$aPics);1011// Check to see if we have at least 1 image12$iNumberOfPics=count($aPics[0]);1314if($iNumberOfPics> 0 ) {15// Now here you would do whatever you need to do with the images16// For this example the images are just displayed17for($i=0;$i<$iNumberOfPics;$i++ ) {18echo$aPics[0][$i];19};20};2122endwhile;23endif;24?>
Code explanation. The above code basically consists of a simple WordPress loop. The only difference is that we use PHP and regular expressions to search for images within the post’s content instead of simply displaying posts. If images are found, they’re displayed.
