0

As stated here How To Retrieve An Image Attachment's Alt Text?

"Image's 'alt' text is stored as a string in wp_postmeta with the meta_key of '_wp_attachment_image_alt'"

I am using below code to print alt tag of attached image...

<? get_post_meta($post->ID, '_wp_attachment_image_alt', true); ?>

But it is not working.

11
  • Did you try to echo get_post_meta($post->ID, '_wp_attachment_image_alt', true); as your code just returns it and not prints it. Sep 21, 2016 at 10:03
  • @AhmedElmahdy yes. i tried that. i forgot to that mentioned because i tried many ways to sort it out. I also tried <?php get_image_tag( $id, $alt, $title, $align, $size ); ?> Sep 21, 2016 at 10:29
  • Can you post please the full code scope where you have tried it and it didn't work? Sep 21, 2016 at 10:30
  • @AhmedElmahdy please check '<a target="_blank" href="<?php the_permalink(); ?>"><img class="hover-img" style="height:235px; width: 100%;" src="<?php the_post_thumbnail_url(); ?>" alt="<? echo get_post_meta($post->ID, '_wp_attachment_image_alt', true); ?>"></a>' Sep 21, 2016 at 10:38
  • Below that code can you test printing $post->ID and tell me what you get? e.g. echo $post->ID; Sep 21, 2016 at 10:39

1 Answer 1

0

Use below code to get attached image title and alt.

//Get attachment title & alt...
$attachment_title = '';
$attachment_alt = '';

$args = array( 'post_type' => 'attachment', 'numberposts' => 1, 'post_status' => null, 'post_parent' => $post->ID, 'post_mime_type' => 'image'); 
$attachments = get_posts($args);

//If attachments exist...
if($attachments) {

  //Loop until attachments...
  foreach( $attachments as $attachment ) {
    $attachment_title = $attachment->post_title;
    $attachment_alt = get_post_meta($attachment->ID, '_wp_attachment_image_alt', true);
  }
}

Hope this hope you well!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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