How to display images in related posts?

I want to display an image for each related post. Note, these are inline images, not from post thumbnails.

What I need is:

Read More
  1. If the post has an only image, show it.
  2. If it has multiple images, show the first one.
  3. If non-images, show a static alternative.

Below is what I have currently.

<?php
$categories = get_the_category($post->ID);
if ($categories) {
    $category_ids = array();
    foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;
    $args=array(
        'category__in' => $category_ids,
        'post__not_in' => array($post->ID),
        'showposts'=> 5, // Number of related posts that will be shown.
        'caller_get_posts'=> 1
    );
    $my_query = new wp_query($args);
    if( $my_query->have_posts() ) {
        echo '<h3>Related Posts</h3>';
        echo '<ul>';
        while ($my_query->have_posts()) {
            $my_query->the_post();
        ?>
            <li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
        <?php
        }
        echo '</ul>';
    }
}
wp_reset_query(); ?>

Related posts

Leave a Reply

1 comment

  1. That is simple:

    <?php
    $categories = get_the_category($post->ID);
    if ($categories) {
        $category_ids = array();
        foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;
       $args=array(
        'category__in' => $category_ids,
        'post__not_in' => array($post->ID),
        'showposts'=> 5, // Number of related posts that will be shown.
        'caller_get_posts'=> 1
    );
    $my_query = new wp_query($args);
    if( $my_query->have_posts() ) {
        echo '<h3>Related Posts</h3>';
        echo '<ul>';
        while ($my_query->have_posts()) {
            $my_query->the_post();
        ?>
            <li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a><?php echo catch_that_image() ?></li>
        <?php
        }
        echo '</ul>';
    }
    }
    wp_reset_query(); ?>
    

    In functions.php add this code:

    function catch_that_image() {
      global $post, $posts;
      $first_img = '';
      ob_start();
      ob_end_clean();
      $output = preg_match_all('/<img.+src=['"]([^'"]+)['"].*>/i', $post->post_content, $matches);
      $first_img = $matches [1] [0];
    
      if(empty($first_img)){ //Defines a default image
        $first_img = "/images/default.jpg";
      }
      return $first_img;
    }
    

    Of course, replace the default image path, and style the output to your needs.

    Code taken from: http://www.wprecipes.com/how-to-get-the-first-image-from-the-post-and-display-it