The wp_get_attachment_image_src()
function expects you to also pass some kind of attachment ID plus it doesn’t grab the image HTML that we need so instead we should use wp_get_attachment_image()
.
IF a post has a post thumbnail, grab it.
ELSE IF the post has any attached images, grab the first one.
ELSE maybe show a placeholder? I’ve defined the else case at the top of the loop as a default.
if( have_posts() ) {
while( have_posts() ) {
the_post();
$image_html=""; // assign placeholder url here?
if( has_post_thumbnail() ) {
$image_html = get_the_post_thumbnail( $post->ID, 'custom-size', array( 'class' => 'img-style' ) );
} else { // We don't have a thumbnail - grab attachments
$media = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => 1,
'post_status' => 'any',
'post_parent' => $post->ID
'post_mime_type' => array( 'image/jpeg', 'image/gif', 'image/png', 'image/bmp', 'image/tiff', 'image/x-icon' );
) );
if( ! empty( $media ) ) {
$image_html = wp_get_attachment_image( $media[0]->ID, 'cusotm-size', false, array( 'class' => 'img-style' ) );
}
}
if( ! empty( $image_html ) ) {
echo '<a href="'. get_permalink() . '">' . $image_html . '</a>';
}
}
}
Note, I haven’t tested the above so feel free to refine it.