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<img src="$imageURI" width="$imageWidth" height="$imageHeight" border="0">\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<img src="$imageURI" width="$imageWidth" height="$imageHeight" border="0">\n";
			break;
		}
	}
}
unset($args);
echo "\t<img src="$imageURI" width="$imageWidth" height="$imageHeight" border="0">\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.


Posted

in

, ,

by

Tags:

Comments

23 responses to “Get URLs, Captions & Titles for Images Attached to Posts in WordPress”

  1. KJ Avatar

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

  2. Stéphane Gallay Avatar

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

  3. Scimmo Avatar

    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]

    1. Mike Avatar

      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?

  4. Stan Avatar
    Stan

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

    1. Mike Avatar

      Why not just use the [gallery] shortcode then?

  5. Ryan Avatar

    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).

  6. Laura Avatar
    Laura

    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!

    1. Mike Avatar

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

  7. Sacha Avatar

    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?

    1. Mike Avatar

      @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.

  8. Mike Avatar

    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!

  9. Lee Avatar
    Lee

    Is this possible with the new featured image? id liek to show the featured image with it’s caption is this possible?

    1. Mike Avatar

      I’m not sure at the moment, however, I would probably get the ID of the thumbnail image using code from here:

      http://codex.wordpress.org/Function_Reference/get_the_post_thumbnail

      And then pull the caption text with my above code from the attachment image.

  10. Chris Murphy Avatar

    Hi Mike, thanks for sharing your solution — I actually found it via your comments on newvibe.com; I also wanted to share an update to your code since it just saved me a tonne of time in researching/trial/error/beer:

    [code]
    /**
    * Retrieves the attachment data such as Title, Caption, Alt Text, Description
    * @param int $post_id the ID of the Post, Page, or Custom Post Type
    * @param String $size The desired image size, e.g. thumbnail, medium, large, full, or a custom size
    * @return stdClass If there is only one result, this method returns a generic
    * stdClass object representing each of the image’s properties, and an array if otherwise.
    */
    function getImageAttachmentData( $post_id, $size = ‘thumbnail’, $count = 1 )
    {
    $objMeta = array();
    $meta;// (stdClass)
    $args = array(
    ‘numberposts’ => $count,
    ‘post_parent’ => $post_id,
    ‘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 )
    {
    $meta = new stdClass();
    $meta->ID = $attachment->ID;
    $meta->title = $attachment->post_title;
    $meta->caption = $attachment->post_excerpt;
    $meta->description = $attachment->post_content;
    $meta->alt = get_post_meta($attachment->ID, ‘_wp_attachment_image_alt’, true);

    // Image properties
    $props = wp_get_attachment_image_src( $attachment->ID, $size, false );

    $meta->properties[‘url’] = $props[0];
    $meta->properties[‘width’] = $props[1];
    $meta->properties[‘height’] = $props[2];

    $objMeta[] = $meta;
    }

    return ( count( $attachments ) == 1 ) ? $meta : $objMeta;
    }
    }
    [/code]

    This method encapsulates the information into a stdClass/Object with property names that reflect the actual fields in the Media Manager, e.g. when you enter the data. It was too cumbersome to refer to the results sets using the generic post_* fields.

    [code]
    Usage:
    getImageAttachmentData( $post->ID, ‘full’ );
    [/code]

    Basically, you can use this method in the_loop in your templates e.g. single.php, page.php or recursively.

  11. Chris Murphy Avatar

    Example output for the method in my previous comment:
    [code]
    stdClass Object
    (
    [ID] => 152
    [title] => This is the image’s title
    [caption] => This is caption text, lorem ipsum
    [description] => Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
    [alt] => This is alternate text
    [properties] => Array
    (
    [url] => http://localhost/cpc-blog-dev/wp-content/uploads/2010/01/Hydrangeas-450×280.jpg
    [width] => 450
    [height] => 280
    )

    )

    [/code]

  12. Yeremi Loli Avatar
    Yeremi Loli

    Hi there…
    Im using the code but when I change the image title on the post and then update the post… the
    $imageTitle = $attachment->post_title;
    Doesnt work, it doesnt update.

    1. Michael J Kormendy Avatar

      Are you changing the image title in the media gallery for that specific image?

  13. Nathan Web Avatar

    perfect, this is just what I needed. Thanks!!

    1. Michael J Kormendy Avatar

      Glad this helped you out!

  14. […] Get URLs, Captions & Titles for Images Attached to Posts in WordPress « Something Interactive Relaterade inlägg :Taxonomy Images BETA « WordPress PluginsWordPress Featured Images – add_image_size() resizing and cropping demo — studiograsshopperWordPress Featured Images – add_image_size() resizing and cropping demo — studiograsshopperHow does WP media uploader create the 3 different sized images, and how can I duplicate it – WordPress – Stack ExchangeProgrammatically Pull Attachments from WordPress Posts – John FordBy Blogsdna […]

  15. Mani Nilchiani Avatar

    Superb. Thanks a lot.