Getting alt text of featured image

I’m trying to get the alt text of our featured image and have it output on the frontend.

Currently my code is

<img class="vehicle-photo" src="https://wordpress.stackexchange.com/questions/312283/<?php echo the_post_thumbnail_url() ?>" alt="<?php the_post_thumbnail_caption();?>" />

But on the frontend, it is outputting as

<img class="vehicle-photo" src="https://wordpress.stackexchange.com/questions/312283/photo url here" alt="">

2 Answers
2

The alt text is stored as post meta on the attachment, and can be retrieved with get_post_meta() combined with get_post_thumbnail_id():

<?php echo get_post_meta( get_post_thumbnail_id(), '_wp_attachment_image_alt', true ); ?>

But if you just use the the_post_thumbnail() function then you don’t need to bother, the img tag will be output for you, with the alt text:

<?php the_post_thumbnail( 'post-thumbnail', ['class' => 'vehicle-photo'] ); ?>

Leave a Comment