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!