• Resolved ryschill

    (@ryschill)


    Hey Guys,

    I found a php file where it has in the code alt=”” which is making all my posts images not have an alt tag. I’d like to put something within the alt=”” that pulls the Alternative Text from the image I’m using in the Media section. Thoughts on how to achieve this?

    To see the code that it currently reads I’ll give you this.
    File Name: template-functions.php

    <div id="<?php echo $id; ?>" class="inside-post-slider flexslider">
            <ul class="slides">
                <?php
                foreach($images as $n=> $img_id){
                    $col = array();
                   // $col['img'] = $img_id;
                    $meta  = $metas[$n];
                    $attachment=wp_get_attachment_image_src($img_id, 'st_normal_thumb');
    
                    $item = '<li> %1$s </li>';
                    $img = sprintf('<img src="%1$s" alt="" />',$attachment[0]);
                    if(isset($meta['url']) && $meta['url']!=''){
                            $img ='<a href="'.$meta['url'].'">'.$img.'</a></h3>';
                    }
    
                    $caption ='';

Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator keesiemeijer

    (@keesiemeijer)

    Try changing this:

    $img = sprintf('<img src="%1$s" alt="" />',$attachment[0]);

    to this:

    <?php
    $alt = get_post_meta( $img_id, '_wp_attachment_image_alt', true );
    $alt = ( !empty( $alt ) ) ? $alt : '';
    $img = sprintf( '<img src="%1$s" alt="%2$s" />', $attachment[0], $alt );
    ?>

    btw:
    consider creating a child theme instead of editing your theme directly – if you upgrade the theme all your modifications will be lost.

    Thread Starter ryschill

    (@ryschill)

    Hey Kees,

    Thanks for helping, unfortunately it looks like when i replace the code you specified with the alternative code it then makes the site appear like a blank white index file.

    Thoughts?

    Moderator keesiemeijer

    (@keesiemeijer)

    Sorry, try it without the php tags

    $alt = get_post_meta( $img_id, '_wp_attachment_image_alt', true );
    $alt = ( !empty( $alt ) ) ? $alt : '';
    $img = sprintf( '<img src="%1$s" alt="%2$s" />', $attachment[0], $alt );

    Thread Starter ryschill

    (@ryschill)

    Hey Kees,

    Worked 😀 Thanks a ton!

Viewing 4 replies - 1 through 4 (of 4 total)

The topic ‘Custom Alt Tags via PHP’ is closed to new replies.