Get the first image from a WordPress post
Below code will display the first image from a WordPress post, ads it within loop.
<?php while ( have_posts() ) { the_post(); if ( has_post_thumbnail() ) { the_post_thumbnail( /* No need for "post-thumbnail" argument, it's the default. */ ); } else { // No post thumbnail, try attachments instead. $images = get_posts( array( 'post_type' => 'attachment', 'post_mime_type' => 'image', 'post_parent' => $post->ID, 'posts_per_page' => 1, /* Save memory, only need one */ ) ); if ( $images ) { echo '<img src="' . wp_get_attachment_image_src( $images[0]->ID, 'post-thumbnail' ) . '" alt="" />'; } } } ?> |