39

I am using an attachment.php file to show large versions of images that have been clicked on elsewhere. I'd like to pull the image alt text as a caption under the image with javascript, but the alt text isn't included when when wp_get_attachment_image_src() is used. I don't think WP has a function to retrieve it, so I need my own. To write that function I need to know...Where is the alt text for an image stored?

My attachment page uses wp_get_attachment_image_src(), which doesn't include the alt text.

<div class = "entry">
<?php 
if ( wp_attachment_is_image( $post->id ) ) : 
    $att_image = wp_get_attachment_image_src( $post->id, "large");?>

    <a href="<?php echo wp_get_attachment_url($post->id); ?>" 
        title="<?php the_title(); ?>" 
        rel="attachment">
    <img class="attached_img" 
        src="<?php echo $att_image[0];?>" 
        width="<?php echo $att_image[1];?>" 
        height="<?php echo $att_image[2];?>"  
        class="attachment-medium" 
        alt="<?php $post->post_excerpt; ?>" />
    </a> 
} <?php endif;?>
</div>

This shows:

<div class = "entry">
    <a href="http://www.example.com/wp-content/uploads/2010/07/photo_namejpg" 
       title="My_Photo_Title" 
       rel="attachment">
       <img class="attached_img" 
            src="http://www.example.com/wp-content/uploads/2010/07/photo_name_and_size.jpg" 
            width="393" 
            height="500"  
            class="attachment-medium" 
            alt="" />
    </a>
</div>  

I'm aware that the $post->post_excerpt is being called in the above code, but I am not sure what to replace it with to get the image's alt attribute.

7 Answers 7

65

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

Attachment

MIME Types

Uploads

Filesystem

HTML

Low Level Image Handling:


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);

6
  • 1
    Well, I can't but help feel a little dopey now that you've said it. I've used wp_get_attachment_imgage() before and completely forgot about it. You are right about what I you thought I actually need. Thanks for the info. You are also right about where the alt meta is stored...I looked in that very place, but it evaded me even though I must have been staring right at it. That's what I get for getting into it at the end of the day. Thanks again!
    – kevtrout
    Aug 31, 2010 at 11:04
  • Hey, no problem. I've asked some really obvious questions in the recent past too on the hackers list only to have the answer be glaringly obvious to be as soon as someone mentioned it. It's easy to miss something here or there. But the real benefit of WordPress Answers is every question and answer becomes a resource for others with similar questions in the future. I even expect I'll google thing I answered but forgot at points in the future! Aug 31, 2010 at 11:44
  • 1
    Quick question: you indicated that wp_get_attachment_image() returns an array of the image src and attributes. It seems to only return html containing the image and it's attributes. Still does the job, just didn't know if you were aware of something not on the function ref: codex.wordpress.org/Function_Reference/wp_get_attachment_image
    – kevtrout
    Aug 31, 2010 at 15:21
  • 1
    @Mike - Just a quick reminder to update the note about wp_get_attachment_image as an array - that stumped me a bit :). Excellent answer otherwise! Jul 12, 2011 at 21:02
  • 1
    Very detailed answer, well done! Apr 23, 2018 at 9:31
6

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.

2
  • Exactly what i was looking for. Does anyone have an idea of its performance? With so many different values it retrieves... I wonder...
    – Larzan
    Jul 16, 2015 at 13:50
  • @Larzan I wouldn't worry about performance - unless you're getting hundreds of images data at the same time...
    – Tom Auger
    Jul 17, 2015 at 14:17
4

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 )); 
}
2

I found out that the Alt text for attachments was stored on a custom meta called "_wp_attachment_image_alt"

So having the attachment's Id, I was able to get the alt text with this code:

<?php echo get_post_meta($attachment_id, '_wp_attachment_image_alt', true) ?>
1

To add to Mike's answer someone might find this useful. You might need to get the specific ID of the attachment, so you can do so by passing the Post ID to get_post_thumbnail_id example:

  $the_img = wp_get_attachment_image( get_post_thumbnail_id( get_the_ID() ) );
0

If you are using WP_Customize_Media_Control() your get_theme_mod() will return the post id but if you are using the new WP_Customize_Image_Control() the get_theme_mod() will return the image url this was how I was able to get the alt text from using the WP_Customize_Image_Control()

Here is how I was able to do it. Hope this helps someone out there

// This is getting the image / url
$feature1 = get_theme_mod('feature_image_1');

// This is getting the post id
$feature1_id = attachment_url_to_postid($feature1);

// This is getting the alt text from the image that is set in the media area
$image1_alt = get_post_meta( $feature1_id, '_wp_attachment_image_alt', true );

Markup

<a href="<?php echo $feature1_url; ?>"><img class="img-responsive center-block" src="<?php echo $feature1; ?>" alt="<?php echo $image1_alt; ?>"></a>
0

If civilizational methods don't work:

alt="<?php echo explode("\"",get_the_post_thumbnail(get_the_ID()))[9]; ?>"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.