Getting metadata out of wordpress images

May 7th, 2010

As I mentioned in my recent post, I have just switched to WordPress platform from my custom CMS system and I wanted to do something that gave me a bit of trouble as I couldn’t find information on how to do it, so I thought I should share my findings.

If you check my portfolio entries, you’ll notice that I have gallery images attached to each entry. The actual “attachment” is done by the portfolio plugin I use. I upload images through the WordPress media library and then mark them as gallery images for portfolio entries. Now, what the plugin didn’t offer and what I wanted to do is to show captions and descriptions of the images.

I noticed that if you go and edit an image in the media library, you can set its metadata there – caption, “Alt” attribute, description and others. So I figured there must be a way to retrieve this information from your theme/plugin files.

All you need in order to get an image metadata is its ID. Apparently, image attachments are technically wordpress posts, so all the regular post functions work on them.

<?php
 
// lets say our image ID is 131
$id= 131;
 
// as image attachments are technically posts, we can retrieve "the post"
$image_post = get_post($id);
 
// image title is actualy the title of the post, so
// to get the image title
$title= get_the_title($id);
// or
$title2= $image_post->post_title;
 
// image description is actually the content of the post, so
// to get the description
$desc= $image_post->post_content;
 
// image captions as stored as the excerpt of the post, so
// to get the caption
$caption= $image_post->post_excerpt;
 
// Alt attribute is stored as post metadata, so
// to get the Alt
$alt= get_post_meta($id, '_wp_attachment_image_alt', true);
 
?>

Now all we need to do in order to show the metadata on the page is to echo the variables.

I hope this helps someone. Thanks for reading!


4 Responses to “Getting metadata out of wordpress images”

  1. [...] This post was mentioned on Twitter by Gabriel Garbin, Stojilovic Daniel. Stojilovic Daniel said: Getting metadata out of WP images – http://bit.ly/byaNQK [...]

  2. Great post!

  3. Great info – been searching for this a while ago and didn’t come across this for some reason – now I’m doing another project that required title and alt text info from just the image ID and your solution worked great.
    Many thanks.

  4. Thank you for this information, just what i was looking for. :)

Leave a Reply