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.

General Code Concept

$size = "thumbnail"; // options: thumbnail, medium, large, full
$args = array(
'numberposts' => null, // change this to a specific number of images to grab
'post_parent' => '25',
'post_type' => 'attachment',
'nopaging' => false,
'post_mime_type' => 'image',
'order' => 'ASC', // change this to reverse the order
'orderby' => 'menu_order ID', // select which type of sorting
'post_status' => 'any'
);
$attachments =& get_children($args);
if ($attachments) {
foreach($attachments as $attachment) {
foreach($attachment as $attachment_key => $attachment_value) {
$imageID = $attachment->ID;
$imageTitle = $attachment->post_title;
$imageCaption = $attachment->post_excerpt;
$imageDescription = $attachment->post_content;
$imageAlt = get_post_meta($imageID, '_wp_attachment_image_alt', true);
// $imageAlt = $attachment->image_alt; // not sure about this one
$imageArray = wp_get_attachment_image_src($attachment_value, $size, false);
$imageURI = $imageArray[0]; // 0 is the URI
$imageWidth = $imageArray[1]; // 1 is the width
$imageHeight = $imageArray[2]; // 2 is the height
echo "$imageURI \n";
echo "$imageWidth \n";
echo "$imageHeight \n";
echo "$imageID \n";
echo "$imageTitle \n";
echo "$imageCaption \n";
echo "$imageDescription \n";
if(count($imageAlt)) {
echo $imageAlt;
}// if '_wp_attachment_image_alt' is not set, echo $alt; shows text like 'Array()'
break;
}
}
}
unset($args); // clear out arguments if using code multiple times in a theme

Practical Usage #1

Use the following to iterate all images from a post
Hint: can use the above example's variables to pull additional info for each.

$size = "medium";
$args = array(
'numberposts' => null,
'post_parent' => $post->ID,
'post_type' => 'attachment',
'nopaging' => false,
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'menu_order ID',
'post_status' => 'any'
);
$attachments =& get_children($args);
if ($attachments) {
foreach($attachments as $attachment) {
foreach($attachment as $attachment_key => $attachment_value) {
$imageID = $attachment->ID;
$imageTitle = $attachment->post_title;
$imagearray = wp_get_attachment_image_src($attachment_value, $size, false);
$imageURI = $imagearray[0]; // 0 is the URI
$imageWidth = $imagearray[1]; // 1 is the width
$imageHeight = $imagearray[2]; // 2 is the height
echo "\t\n";
break;
}
}
}
unset($args);

Practical Usage #2

If you want to get a specific image ..

$size = "medium";
$args = array(
'numberposts' => 2, //change this to the image you want
'post_parent' => $post->ID,
'post_type' => 'attachment',
'nopaging' => false,
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'menu_order ID',
'post_status' => 'any'
);
$attachments =& get_children($args);
if ($attachments) {
foreach($attachments as $attachment) {
foreach($attachment as $attachment_key => $attachment_value) {
$imageID = $attachment->ID;
$imageTitle = $attachment->post_title;
$imagearray = wp_get_attachment_image_src($attachment_value, $size, false);
$imageURI = $imagearray[0]; // 0 is the URI
$imageWidth = $imagearray[1]; // 1 is the width
$imageHeight = $imagearray[2]; // 2 is the height
// move this down below
// echo "\t\n";
break;
}
}
}
unset($args);
echo "\t\n";

The way the code above works is: the foreach loop, loops from the beginning and iterates through, but doesn't output .. until it's done the loop. It loops through 1, populating all of the variables, and then loops through 2, replacing all of the variables with 2's values. Because we changed the number of posts to retrieve, we only retrieve the last one we wanted, in this case the second image!

This can also be changed to work backwards too (ie. we can get the "second last" image). This can be modified to work with any sort of suitable sorting option: alphanumerically, rating, by ID, etc. - all just by changing the orderby and order setting!

Hope this solution works for your custom PHP queries and image retrieval via WordPress' Media gallery.

13 comments:

  1. KJ, 3. August 2009, 4:13

    Thanks for the link back. Glad you managed to find my code useful.

     
  2. Stéphane Gallay, 3. November 2009, 8:38

    Whew! Thanks for this snippet, it was just what I needed to get captions in my theme based on the Arras theme.

     
  3. Scimmo, 9. November 2009, 3:25

    How many pages can be added and pages will be indexed as if the reference to the new directory is not the main page, and a minor? What is the limit of the number of links from the main page? and how many pages are enough to complete the work site? Thanks for understanding!
    ———————————————————————
    [url=http://www.scimmo.de]fun [/url][url=http://www.scimmo.de]fun games [/url][url=http://www.scimmo.de]flash games [/url][url=http://www.scimmo.de]shockwave games [/url]

     
  4. Mike, 22. November 2009, 14:03

    Hey Scimmo, sorry for the late reply, but as I look at your comment post, I’m not sure what you are speaking about. Can you clarify?

     
  5. Stan, 7. February 2010, 18:03

    how can i get all images related to one entry instead of just the first one?

     
  6. Mike, 16. February 2010, 2:04

    Why not just use the [gallery] shortcode then?

     
  7. Ryan, 18. February 2010, 16:44

    Dude…you rock. Thank you for a concise solution that actually works.

    Well…there is one error in your code; after your “foreach” statement, you have a semicolon. You should instead have an opening curly brace (and a corresponding closing brace).

     
  8. Laura, 23. February 2010, 18:01

    Hey Mike, this is a great solution. I, too, would be interested in gathering the data for all images associated with a post because I want to pass the data to an XML file. The gallery tag doesn’t really work for that purpose. If you have any insight or ideas, I’d appreciate it. Thanks for the code!

     
  9. Laura, 23. February 2010, 18:31
     
  10. Mike, 10. March 2010, 20:54

    Glad you found your solution.
    Can you give me some examples of why it might be useful to get this info as such? Examples?

     
  11. Sacha, 19. April 2010, 20:46

    Thanks for your help! But I have a few remarks (which might very well be off the mark since I’m new to wordpress).

    First it seems to me that “attachment_array” is not actually an array, but an object. Also, I’m wondering why you don’t use $attachment_array->post_title to get the title instead of making another query using get_post(), which seems superfluous?

     
  12. Mike, 9. May 2010, 12:55

    @Sacha, good points .. will research this a bit more and make the changes to the post if it speeds things up on the server side.

     
  13. Mike, 30. May 2010, 20:14

    Thank you to everyone’s comments, I have updated the code, fixed some errors, and added some more examples. If there’s anything that needs clarification or more fixes, please let me know!

     

Write a comment: