0

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="<?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="photo url here" alt="">
6

The alt text is stored as 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'] ); ?>
| improve this answer | |
1

Please try code given below:

<?php $image_id = get_post_thumbnail_id(get_the_ID());
$alt_text = get_post_meta($image_id , '_wp_attachment_image_alt', true);?>//Variable name updated

<img class="vehicle-photo" src="<?php echo the_post_thumbnail_url() ?>" alt="<?php echo $alt_text ;?>" />
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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