davidgagne.net

  • About
  • Archives
  • Twitter
  • Facebook
  • bartender.live
  • GitHub
  • LinkedIn

WordPress Wednesday: Thumbnail ALT Tags

February 15th, 2017 @ 8:06 am PST

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.

More posts tagged:
PHP / wordpress / wordpresswednesday

More posts categorized:
blogtech Web Design

More posts from:
February 2017 / 2017

Post navigation

Previous Post
Previous Post Personalized DNA Poster
Next Post
Next Post Radio Dismuke

Search


Awesome Web Hosting

Awesome Web Hosting

I've trusted DreamHost to power this website – and nearly 100 other ones – since March 22, 2001. They have great prices, excellent customer support, and a killer web interface to manage your domains.

  • Get Your Own Website

© David Vincent Gagne. All rights reserved. Custom WordPress Theme by Jacket Industries.