Automatically Get Images on Post Content


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.

    01 <?php if (have_posts()) : ?>
    02 <?php while (have_posts()) : the_post(); ?>
    03
    04 <?php
    05 $szPostContent = $post->post_content;
    06 $szSearchPattern = '~<img [^\>]*\ />~';
    07
    08 // Run preg_match_all to grab all the images and save the results in $aPics
    09 preg_match_all( $szSearchPattern, $szPostContent, $aPics );
    10
    11 // Check to see if we have at least 1 image
    12 $iNumberOfPics = count($aPics[0]);
    13
    14 if ( $iNumberOfPics > 0 ) {
    15 // Now here you would do whatever you need to do with the images
    16 // For this example the images are just displayed
    17 for ( $i=0; $i < $iNumberOfPics ; $i++ ) {
    18 echo $aPics[0][$i];
    19 };
    20 };
    21
    22 endwhile;
    23 endif;
    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.

Sources:

Hot Trending Topics

  1. WordPress Trick: Add Gravatar for post author
  2. Adding Background Images to Your Email
  3. 8 Useful WordPress SQL Hacks
  4. Display recent post from specific category (WordPress Trick)
  5. Using Normal Quotes Instead of Curly Quotes

Comments