Get Attachment Alt Text, Caption, Description and Title Programmatically

Every time I work with WordPress attachments I always forget what is what, for example:

  • What is the name of the alt text meta field?
  • How to get an image caption programmatically?

Probably after publishing this tutorial I will never forget that again, but I really hope that it will be helpful for you guys.

So, the long story short, in this tutorial I am going to show you how you can get the following attachment data programmatically:

WordPress attachment information – alt text, caption, title and description

Let’s dive into it right now!

How to Get Alt Text of an Attachment

Since the alt text of an image is stored as post meta data, we can easily use get_post_meta() function over here:

$alt_text = get_post_meta( $image_id, '_wp_attachment_image_alt', true );

How to Get a Title

Title, Caption and Description are a part of a WP_Post object, that’s why either using get_post_field() or get_post() is an option here.

$title = get_post_field( 'post_title', $image_id );

How to Get a Caption of an Attachment

$caption = get_post_field( 'post_excerpt', $image_id );

How to Get a Description

$description = get_post_field( 'post_content', $image_id );

How it Really Works?

If case you didn’t know, media files in WordPress are just a custom post type attachment, it means that:

  • They don’t have a separate table in the WordPress database and the attachment data is stored in wp_posts and wp_postmeta tables.
  • To work with attachments you can use the same functions you use when working with regular WordPress posts, for example get_posts(), get_post(), get_post_meta() etc.

And right now let’s try to replace mutiple usages of the get_post_field() function with a single usage of get_post() one (but there is nothing to worry about, you can use get_post_field() as many times as you like because the WP_Post object is cached anyway).

$attachment = get_post( $image_id );

// easily get an attachment title from WP_Post object
$title = $attachment->post_title;

// get caption
$caption = $attachment->post_excerpt;

// get description
$description = $attachment->post_content;

// in order to get an alt text we still need to use the get_post_meta() function
$alt_text = get_post_meta( $image_id, '_wp_attachment_image_alt', true );

Sometimes my students try to use _wp_attachment_description or _wp_attachment_caption meta keys to get a description or a caption accordingly but I hope now you understand why it doesn’t work that way 🙂

Misha Rudrastyh

Misha Rudrastyh

Hey guys and welcome to my website. For more than 10 years I've been doing my best to share with you some superb WordPress guides and tips for free.

Need some developer help? Contact me

Follow me on X