Support

Account

Home Forums General Issues Post Object: getting featured image alt tag

Solved

Post Object: getting featured image alt tag

  • I need to grab the alt tag for a featured image – I know how to get it normally but when I’m displaying the post via a Post Object I just get the error:

    Warning: Use of undefined constant ‘_wp_attachment_image_alt’ – assumed ‘‘_wp_attachment_image_alt’’ (this will throw an Error in a future version of PHP) in [url to template] on line 106

    Below is my code (commented out bits not working):

    $post_object = get_field('hp_project1');
    
        if( $post_object ): 
    
        $post = $post_object;
        setup_postdata( $post ); 
    
        $thumb = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'large' );
        //$thumb_id = get_post_thumbnail_id( $post->ID );
        //$thumb_alt = get_post_meta($thumb_id, ‘_wp_attachment_image_alt’, true);

    This will give me the image url fine:
    <?php echo $thumb[0]; ?>

    but
    <?php echo $thumb_alt; ?>

    will not give me the alt tag, which would normally work when not grabbing it via a acf post object.

    I google this for about an hour but couldn’t find anything specifically for grabbing it via Post Objects.

  • Right, I’ve finally got to the bottom of this after much googling.

    The issue is $post->ID. It looks like the global $post is not accessible at that point when you’re using the standard (working code) when the variable is through a Post Object.

    Changing it to this, seems to have done the trick:

    $thumb = wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ), 'large' );
    $thumb_id = get_post_thumbnail_id( get_the_ID() );
Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.