Get Image ALT Attribute Using Attachment ID

When using the_post_thumbnail() it will automatically generated the whole img tag.

But if using a custom output and manually generate the img element you need a way to figure out which value to use for the alt attribute. Here’s a function that helps you get the value for alt attribute based on the media attachment ID.

Simplest way is to just get the actual ALT value from the Media Library:

1

get_post_meta($attachment_ID,'_wp_attachment_image_alt',true);

But let’s make that into a reusable function and also take it a bit further and make it less possible to end up without an ALT value.

The code is commented so you can understand what’s going on, but basically the way we get the value for ALT is we check to see if an actual ALT value is set, if not we use the caption and if no caption is set we use the title.