phpwordpressimagealt

Adding alt text to images within a wordpress slider


I am looking to add Alt text to slider images. I was able to add the line:

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

This line pulled in the alt text for the photos but it is the same alt text for all the photos within the slider. It doesn't seem to loop each alt text to each photo. Below is the code that pulls the images.

<?php $_gallery = get_field('project_gallery_photos'); ?>

        <?php if( $_gallery ) { ?>
            <div class="_featured-images">
                <div class="_slider">
                    <?php foreach( $_gallery as $_img ): ?>
                        <div class="_slide">
                            <img src="<?= $_img['photo']['sizes']['project-images']?>" alt ="<?= $alt = get_post_meta(get_post_thumbnail_id($post->ID), '_wp_attachment_image_alt', true); ?>"/>

                            <?php if( $_img['photo_title'] || $_img['photo_caption'] ) { ?>
                                <div class="_caption">
                                    <?= $_img['photo_title']? '<b>'.$_img['photo_title'].'</b><br>': '' ?>
                                    <?= $_img['photo_caption'] ?>
                                </div>
                            <?php } ?>
                        </div>
                    <?php endforeach; ?>
                </div>

Solution

  • What you're pulling in as the meta description for the "featured image" of the current global $post, which the gallery photos appear to be Advanced Custom Field for.

    What you should be pulling in instead would be one of those settings from the foreach() loop. If you're using the standard ACF Pro Gallery field, the alt attribute is included at the first level of the array.

    alt="<?= esc_attr( $_img['alt'] ); ?>"
    

    Otherwise, you should be able to use print_r( $_img ); to find the attribute you need, for instance if your $_img contains a 'photo' key, you may need to use:

    alt="<?= esc_attr( $_img['photo']['alt'] ); ?>"
    

    Documentation & Function Reference