Need Hosting? Get discounted hosting from Hostmonster now.

Latest Tweets from Kreeaytiv

Like Kreeaytiv on Facebook

+1 Kreeaytiv on Google

Contact Kreeaytiv

Interested in a quote from Kreeaytiv? Have a question about a project? Feeling lonely? Use the form below!








Fetching Featured Image Metadata in WordPress

"Rainbow" by John-Morgan via Flickr

Oh look, a featured image in a post about featured images... "Rainbow" by John-Morgan via Flickr

You know what’s awesome? Featured Images in WordPress.

Introduced in WordPress 2.9 (and sometimes called “Post Thumbnails”), this feature lets you do more with images in your WordPress theme development. You can dictate with more flexibility where in your design the image is displayed, as well as leverage the built-in image resizing to make fool-proofing image use a breeze.

But what’s not immediately obvious is how to fetch metadata associated with any image uploaded as a Featured Image. How can you use information like the image title, caption, or alt text?

Bust the below PHP and you’re all set:

<?php function the_post_thumbnail_meta() {
global $post;
$thumb_id = get_post_thumbnail_id($post->id);
$args = array(
'post_type' => 'attachment',
'post_status' => null,
'post_parent' => $post->ID,
'include' => $thumb_id
);
$thumbnail_image = get_posts($args);
if ($thumbnail_image && isset($thumbnail_image[0])) {
echo $thumbnail_image[0]->post_title;
}
}
?>

It’s nothin’ too fancy… basically we’re just grabbing the featured image’s ID, and using that, retrieving whatever info from the image we want.

As written above, this function nabs the Title of the image. However, if you replace…

echo $thumbnail_image[0]->post_title;

…with…

echo $thumbnail_image[0]->post_excerpt;

…you’ll instead fetch the image’s Caption.

You can use the following:

echo $thumbnail_image[0]->post_content;
$alt = get_post_meta($thumbnail_id, '_wp_attachment_image_alt', true);
if(count($alt)) echo $alt;

…to get the image’s Description (first line only) or Alternate Text (last 2 lines only) instead.

Being able to access this information is quite useful, and should offer some more options with your site/theme development. For example, I’ve used the above move to optionally display the featured image’s description in a separate column from the one the image itself is displayed in (which is also a different column from the one where the actual post content is displayed).

Kick it nerds!

P.S. If you haven’t messed with Featured Images much yet, peep this post, it’s a great summary and introduction to what’s possible.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>