Mar
30

Automatically Get Images on Post Content

sm4

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.

  1. Paste the following code anywhere in your theme. 
post_content;
$szSearchPattern = '~<img alt="" />]*\ /&gt;~';
 
// Run preg_match_all to grab all the images and save the results in $aPics
preg_match_all( $szSearchPattern, $szPostContent, $aPics );
 
// Check to see if we have at least 1 image
$iNumberOfPics = count($aPics[0]);
 
if ( $iNumberOfPics &gt; 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 &lt; $iNumberOfPics ; $i++ ) {
          echo $aPics[0][$i];
     };
};
 
endwhile;
endif;
?&gt;

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.





Related posts


Want automatic updates? Subscribe to our RSS feed or
Get Email Updates sent directly to your inbox!