Get URLs, Captions & Titles for Images Attached to Posts in Wordpress
I’ve been working on a new Wordpress theme for my client that involves a billboard concept where certain posts are categorized as homepage billboard items, and those post items have images attached to them within the Media gallery of Wordpress. I found out how to pull out the URI address of the images that are attached to the posts, but it took me some time to figure out how to get the Title, Caption and Description text associated directly with that image attachment.
I borrowed most of my code from here, but I think my example illustrates the concept of retrieving the data needed much easier.
// within the loop...
// gets last image from media library that are attached to current post
$attachments =& get_children( 'post_type=attachment&post_mime_type=image&post_parent=' . get_the_id() );
if (empty($attachments)) {
$imageURI = "/location/to/default/image.jpg";
$imageTitle = "Default Title Text";
$imageCaption = "Default Caption Text";
$imageDescription = "Default Description Text";
}
else {
foreach($attachments as $attachment => $attachment_array );
$imagearray = wp_get_attachment_image_src($attachment, 'full', false);
$imageURI = $imagearray[0];
$imageID = get_post($attachment);
$imageTitle = $imageID->post_title;
$imageCaption = $imageID->post_excerpt;
$imageDescription = $imageID->post_content;
}
echo $imageURI;
echo $imageTitle;
echo $imageCaption;
echo $imageDescription;
Hope this solution works for your custom PHP queries and image retrieval via Wordpress' Media gallery.
