Software Developer

Get Attachment ID of an Image For a Post When It’s Not Set As Featured

A function to get the attachment id of the first image attachment of a post, given the id of the post. Useful if you need the ID of an image that’s attached to a post when that image is not set as the post thumbnail (or featured image). This returns the image ID.

/**
 * returns the attachment ID of the first attached image found for a post.
 * @param post ID of the parent post
 */
function isa_get_attachment_id($parentid) {
			$attachments = get_children( array(
			                'post_parent'    => $parentid,
			                'post_type'      => 'attachment',
			                'numberposts'    => 1, // show all -1
			                'post_status'    => 'inherit',
			                'post_mime_type' => 'image',
			                'order'          => 'ASC',
			                'orderby'        => 'menu_order ASC'
			                ) );
			foreach ( $attachments as $attachment_id => $attachment ) {
			    return $attachment_id;
			}
		
	}

By

Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this:

[code]

YOUR CODE HERE 

[/code]