Query to show images with recent posts in WordPress sidebar/widget

To show recent items from a WordPress category in a widget I’m using this code…

<ul>
<?php $recent = new WP_Query("cat=1231&showposts=5"); while($recent->have_posts()) : 
$recent->the_post();?>
<li><a href="<?php the_permalink() ?>" rel="bookmark">
<?php the_title(); ?>
</a></li>
<?php endwhile; ?>
</ul>

…but how can I make this query also display the first image in each post, and is there any way to set a ‘default’ image in case there is no image?

Read More

Is there also a way to use thumbnails here, rather than loading the full size image and using HTML to resize?

Related posts

Leave a Reply

1 comment

  1. This is probably what you are looking for, found here

    function get_first_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;
    }