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?
First of all you need to get
attachment ID
for gettingalt
text..Use this code to get that,
Now add your code,
Make sure that, your
attachment Alternative Text
is not empty…You can add
Alternative Text
fromwp-admin --> Media --> edit your attachment --> Alternative Text
…Can you please try below code:
I found a script, try if this works for you. Add this in your theme’s functions.php file
function isa_add_img_title( $attr, $attachment = null ) {
}
add_filter( ‘wp_get_attachment_image_attributes’,’isa_add_img_title’, 10, 2 );
I found this script working on my end, similar from Mukesh Panchal. I’ve tried other script from other but it didn’t work.
The code below fixes this. When a page loads, it finds all of the images that are missing alt text and looks to see if youâve specified an alt text for it in the Media Library. If so, it updates the image before loading the page.