How to get image title/alt attribute?

Came here as this post is among the top hits on the search engine when looking for WordPress image alt and title. Being rather surprised that none of the answers seem to provide a simple solution matching the question’s title I’ll drop what I came up with in the end hoping it helps future readers.

// An attachment/image ID is all that's needed to retrieve its alt and title attributes.
$image_id = get_post_thumbnail_id();

$image_alt = get_post_meta($image_id, '_wp_attachment_image_alt', TRUE);

$image_title = get_the_title($image_id);

As a bonus here’s how to retrieve an image src. With the above attributes that’s all we need to build a static image’s markup.

$size="my-size" // Defaults to 'thumbnail' if omitted.

$image_src = wp_get_attachment_image_src($image_id, $size)[0];

Leave a Comment