babusi
babusi

Reputation: 520

Get Wordpress Featured Image "alt"

I'm trying to get a page's featured image alt and echo it as paragraph text but my code doesn't seem to be working.

I'm currently able to echo the image and it's working perfectly.

Here's the code I'm using:

    <?php
    get_header(); ?>
      </div>
    <?php /* The loop */ ?>
    <?php while ( have_posts() ) : the_post(); ?>
    <div class="header-image">

    <?php echo get_the_post_thumbnail($page->ID, 'full'); ?> 
    
    <?php $alt = get_post_meta( $attachment_img->ID, '_wp_attachment_image_alt', true ); ?>
    
    <p><?php echo $alt; ?></p>
    
    </div>

Upvotes: 9

Views: 37873

Answers (3)

Michiel J Otto
Michiel J Otto

Reputation: 2311

If you want to get the alt text of your featured image, you can get it with this code...

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

So if you want to place it in a P tag, this will work...

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

Hope it helps you, or someone at least.

Upvotes: 5

gregmatys
gregmatys

Reputation: 2198

Check if you get correct thumbnail id.
For me this code works perfect:

$thumbnail_id = get_post_thumbnail_id( $post->ID );
$alt = get_post_meta($thumbnail_id, '_wp_attachment_image_alt', true);

Upvotes: 33

Dzhuneyt
Dzhuneyt

Reputation: 8701

Here's a solution:

  $thumbnail_id    = get_post_thumbnail_id($post->ID);
  $thumbnail_image = get_posts(array('p' => $thumbnail_id, 'post_type' => 'attachment'));

  if ($thumbnail_image && isset($thumbnail_image[0])) {
    echo '<span>'.$thumbnail_image[0]->post_excerpt.'</span>';
  }

Or you can use your code, but instead of echoing $alt directly you need to echo $alt->post_excerpt.

Upvotes: 4

Related Questions