How to get image title/alt attribute?

In my white theme, there is no alt attribute configured for the home slider post. I added the alt text for the image through the media library interface. I added the following code to display the alt text/attribute. But it does not display:

<img class="homepage-slider_image" src="" alt="" />

Here is the code:

  $image = get_post_meta(get_the_ID(), WPGRADE_PREFIX.'homepage_slide_image', true);
  if (!empty($image)) {
    $image = json_decode($image);
    $image_alt = get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true);
    if ( empty( $image_alt )) {
      $image_alt = $attachment->post_title;
    if ( empty( $image_alt )) {
      $image_alt = $attachment->post_excerpt;
    $image_title = $attachment->post_title;
    $image_id = $image->id;
    $image = wp_get_attachment_image_src( $image_id, 'blog-huge', false);
    echo '<img class="homepage-slider_image" src="'.$image[0].'" alt="'. $image_alt .'" />';


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