Get The First Image of a WordPress post

firstLately I've been doing a lot of WordPress plugin development and one of the plugins I am developing needed to display a list of posts with an image against each post.

Some of the posts had featured images and other had images inside the content.

To make sure that every item in the list had an image against it, I decided to go down the following route :

  1. for each post/list entry see if it had a featured image attached. If so, get it and exit
  2. If no featured image attached, then get the first image from the post's content.

I could have used regex to get the first img, but WordPress already has some neat built in functions to do this, so this is what I came up with:

function first_image( $postID=0, $size="thumbnail" ) {
	$args = array(
		'numberposts' => 1,
		'order' => 'ASC',
		'post_mime_type' => 'image',
		'post_parent' => $postID,
		'post_status' => null,
		'post_type' => 'attachment',
	);

	$attachments = get_children( $args );

	if ( $attachments ) {
             $img = array_shift($attachments);
	     $image = wp_get_attachment_image_src( $img->ID, $size );
      return $image[0];
	} else {
    return NULL;
  }
}

The function takes a post_id as an argument and an optional image size.

It returns the full URL of the image for you to use as you wish.

It makes great use of WP_Query and the hidden gem of a function called "get_children"

I hope it makes someone else's life easier..

 

Leave a Reply

Your email address will not be published. Required fields are marked *