Wordpress - How To Retrieve An Image Attachment's Alt Text?

I recently did some research for a client project recently so lo-and-behold I get to use it here!

After the text you'll see a categorized list of most (all?) of the image handling functions from within WordPress 3.0.1 (I grouped them in some semblance of order but don't put too much credence in my categorization.)

Anyway, answering what (I think) you need instead of what you asked for (okay, I'll answer that too, at the end) I think what you need is the wp_get_attachment_image() function which will return an HTML string containing these attributes:

  • 'src',
  • 'class',
  • 'alt' and
  • 'title'.

WordPress 3.0 Image Handling Functions

So here are WordPress' image handling functions for your and other's reference (jump below for the answer to your exact question):

Image Support/Thumbnails

  • set_post_thumbnail_size( $width = 0, $height = 0, $crop = FALSE )
  • add_image_size( $name, $width = 0, $height = 0, $crop = FALSE )
  • get_intermediate_image_sizes()
  • wp_constrain_dimensions( $current_width, $current_height, $max_width=0, $max_height=0 )

Attachment

  • get_attached_file( $attachment_id, $unfiltered = false )
  • is_local_attachment($url)
  • update_attached_file( $attachment_id, $file )
  • wp_attachment_is_image( $post_id = 0 )
  • wp_count_attachments( $mime_type = '' )
  • wp_delete_attachment( $post_id, $force_delete = false )
  • wp_get_attachment_image($attachment_id, $size = 'thumbnail', $icon = false, $attr = '')
  • wp_get_attachment_image_src($attachment_id, $size='thumbnail', $icon = false)
  • wp_get_attachment_metadata( $post_id = 0, $unfiltered = false )
  • wp_get_attachment_thumb_file( $post_id = 0 )
  • wp_get_attachment_thumb_url( $post_id = 0 )
  • wp_get_attachment_url( $post_id = 0 )
  • wp_insert_attachment($object, $file = false, $parent = 0)
  • wp_update_attachment_metadata( $post_id, $data )

MIME Types

  • wp_match_mime_types($wildcard_mime_types, $real_mime_types)
  • wp_mime_type_icon( $mime = 0 )
  • wp_post_mime_type_where($post_mime_types, $table_alias = '')

Uploads

  • media_handle_upload()

Filesystem

  • _wp_relative_upload_path( $path )
  • wp_upload_dir( $time = null )

HTML

  • get_image_tag($id, $alt, $title, $align, $size='medium')

Low Level Image Handling:

  • wp_load_image( $file )
  • image_constrain_size_for_editor($width, $height, $size = 'medium')
  • image_downsize($id, $size = 'medium')
  • image_get_intermediate_size($post_id, $size='thumbnail')
  • image_hwstring($width, $height)
  • image_make_intermediate_size($file, $width, $height, $crop=false)
  • image_resize( $file, $max_w, $max_h, $crop = false, $suffix = null, $dest_path = null, $jpeg_quality = 90 )
  • image_resize_dimensions($orig_w, $orig_h, $dest_w, $dest_h, $crop = false)

As promised the Image's 'alt' text is stored as a string in wp_postmeta with the meta_key of '_wp_attachment_image_alt'.

As you probably already know you can load it with a simple get_post_meta() like so:

$alt_text = get_post_meta($post->ID, '_wp_attachment_image_alt', true);


Consider looking at wp_prepare_attachment_for_js( $attachment ), where $attachment is the WP_Post object of the attachment itself.

This is a bit of a "kitchen sink" function, but it does provide a very nice hash with a ton of metadata, including 'alt':

$response = array(
        'id'          => $attachment->ID,
        'title'       => $attachment->post_title,
        'filename'    => wp_basename( $attachment->guid ),
        'url'         => $attachment_url,
        'link'        => get_attachment_link( $attachment->ID ),
        'alt'         => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
        'author'      => $attachment->post_author,
        'description' => $attachment->post_content,
        'caption'     => $attachment->post_excerpt,
        'name'        => $attachment->post_name,
        'status'      => $attachment->post_status,
        'uploadedTo'  => $attachment->post_parent,
        'date'        => strtotime( $attachment->post_date_gmt ) * 1000,
        'modified'    => strtotime( $attachment->post_modified_gmt ) * 1000,
        'menuOrder'   => $attachment->menu_order,
        'mime'        => $attachment->post_mime_type,
        'type'        => $type,
        'subtype'     => $subtype,
        'icon'        => wp_mime_type_icon( $attachment->ID ),
        'dateFormatted' => mysql2date( get_option('date_format'), $attachment->post_date ),
        'nonces'      => array(
            'update' => false,
            'delete' => false,
            'edit'   => false
        ),
        'editLink'   => false,
        'meta'       => false,
    );

This is particularly useful (as the name implies), for sending the attachment image meta to a wp.media View via wp_send_ajax(), but that doesn't mean you couldn't use it for other purposes.

I like abstracting away from the _wp_attachment_image_alt post meta field, in case the method to retrieve the alt text ever changes (unlikely, but conceivable).

I do feel that there's a case for a wp_get_attachment_image_alt() method however.


Mike's answer is correct, of course, but $alt_text = get_post_meta($post->ID, '_wp_attachment_image_alt', true); may return an empty string.

wp_get_attachment_image, however, does always get an alt_text.

The Wordpress team applies the following trick, first, checking for the post_except, then obtaining the title.

if(empty($alt_text)) // If not, Use the Caption
{
    $attachment = get_post($post->ID);
    $alt_text = trim(strip_tags( $attachment->post_excerpt ));
}
if(empty($alt_text)) // Finally, use the title
{ 
    $attachment = get_post($post->ID);
    $alt_text = trim(strip_tags( $attachment->post_title )); 
}