Create A Loop Of Images

To create our loop of images, we first need a PHP function that can grab the first image from each post and return its URL. To do this, paste the following function in your functions.php file. Don’t forget to define a default image on line 10.


function catch_that_image() {
  global $post, $posts;
  $first_img = '';
  $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;

Once you’ve saved the functions.php file, you are now ready to display your image loop.

if (have_posts()) :
    while (have_posts()) : the_post(); ?>
        <a href="<?php the_permalink();?>" title="<?php the_title(); ?>">
        <img src="<?php echo catch_that_image() ?>" alt="<?php the_title(); ?>" />