Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 585
user3254973 Avatar asked Oct 17 '25 05:10

user3254973


2 Answers

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...

like image 86
Akshay Paghdar Avatar answered Oct 19 '25 22:10

Akshay Paghdar


Can you please try below code:

<?php
$thumb_id = get_post_thumbnail_id(get_the_ID());
$alt = get_post_meta($thumb_id, '_wp_attachment_image_alt', true);
if( $alt ):
    echo $alt;
endif;
?>
like image 43
Mukesh Panchal Avatar answered Oct 19 '25 21:10

Mukesh Panchal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!