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.