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="" />';
			}
		}
	}
?>

Related posts:

HTML5 page structure

HTML5 offers more powerful structure comparing to older versions of Html. There are many new …


Partner with Us

We are providing an exclusive partnership offer to individuals and companies who are interested in setting up their own web design & development company. For more information about how to partner with us, please contact us