How to grab an image ALT tag from the WordPress Media system

WordPress Wednesday: Thumbnail ALT Tags

If you’re editing a WordPress theme that uses thumbnails, you might want to check to see if it’s properly embedding ALT tags on them. Many of the themes available are either using the title of the post (which is redundant), including an empty ALT tag (which is useless), or simply aren’t including it at all (which is bad). You can fix that pretty easily with a smidge of PHP.

At the bare minimum an IMG tag should include a SRC and an ALT, like this:

<img src="//somedomain.com/path/image.jpg" alt="my cat">

You probably already know how to grab a post’s thumbnail image, and you’re a good developer so you’re checking to make sure the post even has one first:

if ( has_post_thumbnail() ){
     echo '<img src="';
     the_post_thumbnail_url('featured-small');
     echo '">';
}

If you want to use the ALT text you’ve assigned the image in the WordPress Media Library, you can do it by grabbing the post_meta for the _wp_attachment_image_alt field, like this:

if ( has_post_thumbnail() ){
     echo '<img src="';
     the_post_thumbnail_url('featured-small');
     echo '" alt="';
     $post_thumbnail_id = get_post_thumbnail_id();
     $thumbnail_alt = get_post_meta( $post_thumbnail_id, '_wp_attachment_image_alt', true);
     if ( strlen( $thumbnail_alt ) ){
          echo $thumbnail_alt;
     }
     else{
	the_title();
     }
     echo '">';
}

You’ve already checked to make sure the post has a thumbnail, so calling get_post_thumbnail_id() should definitely return its value. Then you can use get_post_meta() to find the value the author used for the ALT tag in the WordPress Media Library. And then, just to be on the safe side, make sure it’s not empty. If it is, then you can fall back to using the title of the post.

Post the first comment:

I'll never share your email address and it won't be published.

What Is This?

davidgagne.net is the personal weblog of me, David Vincent Gagne. I've been publishing here since 1999, which makes this one of the oldest continuously-updated websites on the Internet.

bartender.live

A few years ago I was trying to determine what cocktails I could make with the alcohol I had at home. I searched the App Store but couldn't find an app that would let me do that, so I built one.

Hemingway

You can read dozens of essays and articles and find hundreds of links to other sites with stories and information about Ernest Hemingway in The Hemingway Collection.