dsebao
6/12/2013 - 3:03 AM

Detect images attached to post - WordPress

Detect images attached to post - WordPress

//In your template, where do you want to show the image of the post

<?php while ( have_posts() ) : the_post();?>

<article>
  <?php if(my_image($post->ID, 'thumbnail') != ''){?>
    <a href="<?php the_permalink();?>">
      <img alt="<?php the_title();?>" title="<?php the_title();?>" src="<?php echo my_image($post->ID, 'thumbnail'); ?>"/>
    </a>
  <?php }?>
</article>

<?php endwhile;?>
<?php
//PASTE THIS IN FUNCTIONS

function my_image($postid=0, $size='thumbnail') { //it can be thumbnail or full
  if ($postid<1){
    $postid = get_the_ID();
  }
  if(has_post_thumbnail($postid)){
    $imgpost = wp_get_attachment_image_src(get_post_thumbnail_id($postid), $size);
    return $imgpost[0];
  }
  elseif ($images = get_children(array( //If you upload an image function gets first image
    'post_parent' => $postid,
    'post_type' => 'attachment',
    'numberposts' => '1',
    'orderby' => 'menu_order',
    'order' => 'ASC', //If reverse use DESC
    'post_mime_type' => 'image', )))
    foreach($images as $image) {
      $thumbnail=wp_get_attachment_image_src($image->ID, $size);
      return $thumbnail[0];
    }
}
?>