Support » Developing with WordPress » How to get the alt text of an image

  • Resolved pierremg

    (@pierremg)


    Some things that should be really simple to do with WP are hard to achieve. I’ve been looking for this on Google for the last 3 hours and I still couldn’t get anything that works. My problem is that I need to take full control of the size of feature images and the easiest way I found to do that is using the following code:

    <img title="" alt="" class="wp-post-image" 
                 src="<?=wp_get_attachment_url( get_post_thumbnail_id() ); ?>" style="width:100%; height:auto;">

    The problem? The alt attribute will stay empty and I don’t want that. So I need a function that allows me to get the alt of a feature image.

Viewing 5 replies - 1 through 5 (of 5 total)
  • Moderator t-p

    (@t-p)

    pierremg

    (@pierremg)

    Not at all, it’s not even to what I need. I know what alt and title are, and I always set those attributes when I upload an image. What I’m trying to achieve is to “extract” the alt attribute from the WP database. For example, I need something like this:

    <img title="" alt="<?php any_function_that_can_help_me() ?>" >

    but thanks anyway

    Use the the_post_thumbnail() function. It will include the image tag with alt text automatically. You can use the 2nd argument to pass any other attributes you might want (like class).

    That’s what I recommend you do, but to answer the original question, the alt text is metadata on the attachment post, and can be retrieved with:

    get_post_meta( $attachment_id, '_wp_attachment_image_alt', true );
    

    If you’re getting it for the post thumbnail then set $attachment_id to get_post_thumbnail_id().

    pierremg

    (@pierremg)

    I can’t use the_post_thumbnail() because this function also automatically adds “width” and “height” to the img tag and that’s what I’m trying to avoid.

    pierremg

    (@pierremg)

    Thanks @jakept. This is how I got it working:

    <?php
    $thumb_id = get_post_thumbnail_id(get_the_ID());
    $alt = get_post_meta($thumb_id, '_wp_attachment_image_alt', true);
    if(count($alt)) echo $alt;
    ?>
    <img title="" alt="<?php echo $alt; ?>" class="wp-post-image" 
                 src="<?=wp_get_attachment_url( get_post_thumbnail_id() ); ?>" style="width:100%; height:auto;">
Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘How to get the alt text of an image’ is closed to new replies.