how do i retrieve and display the alt text of an image in wordpress?

alt, image, php, wordpress

Solution

First of all you need to get `attachment ID` for getting `alt` text..

Use this code to get that,

$img_id = get_post_thumbnail_id(get_the_ID());

Now add your code,

<?php $alt_text = get_post_meta($img_id , '_wp_attachment_image_alt', true); ?>
<h1 class="entry-title"><?php echo $alt_text; ?></h1>

Make sure that, your `attachment Alternative Text` is not empty...

You can add `Alternative Text` from `wp-admin --> Media --> edit your attachment --> Alternative Text`...

Problem

how do i retrieve and display the alt text of an image in wordpress? trying to substitute the title for the alt. here is the original code. ``` <?php while ( have_posts() ) : the_post(); ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <header class="entry-header"> <h1 class="entry-title"><?php the_title(); ?></h1> ``` so in the h1 i want: ``` <h1 class="entry-title">"alt text of image"</h1> ``` tried putting it in a variable like so: ``` $alt_text = get_post_meta($img_id , '_wp_attachment_image_alt', true); <h1 class="entry-title"><?php echo $alt_text; ?></h1> ``` but it doesn't show up. any solutions?

Original source