Skip to content

Instantly share code, notes, and snippets.

@wycks
Created November 1, 2012 02:25
Show Gist options
  • Save wycks/3991250 to your computer and use it in GitHub Desktop.
Save wycks/3991250 to your computer and use it in GitHub Desktop.
Image loop fallback that grabs the first image attached to post if there is no featured image.
<?php
$attachments = get_children(
array(
'numberposts' => 1,
'order'=> 'ASC',
'post_mime_type' => 'image',
'post_parent' => get_the_ID(),
'post_status' => null,
'post_type' => 'attachment'
));
//first check for featured image
if ( has_post_thumbnail() ) {
the_post_thumbnail('thumbnail');
} elseif ($attachments) {
if ( ! is_array($attachments) ) continue;
//image settings
$args = array(
'src' => $src,
'class' => "attachment-$size",
'alt' => trim(strip_tags( get_post_meta($attachment_id, '_wp_attachment_image_alt', true) )),
'title' => trim(strip_tags( $attachment->post_title )),
);
$first_attachment = reset($attachments);
echo wp_get_attachment_image($first_attachment->ID, 'thumbnail', $args);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment