Find WordPress featured images with no alt text
WordPress allows you to set a featured image - called a "thumbnail" in the API. This gives a single image which can be used on a listing page, or shown when a post is shared on social media.
The WordPress Media Library lets you set the alt text of an image. But, crucially, this alt text can be different when the image is used as a featured image.
Here's how to find all your featured images which don't have alt text.
One Liner
Paste this into wp shell
to get a list.
PHPforeach (get_posts( array( 'post_type' => 'post', 'post_status' => array('publish'), 'posts_per_page' => -1,) ) as $post) { if( simplexml_load_string( get_the_post_thumbnail($post) )["alt"] == "") { echo $post->post_date . " " . get_site_url(). "/wp-admin/post.php?post=" . $post->ID . "&action=edit " . $post->post_title . "\n"; } }
An explanation
To get the image element of the featured image, use get_the_post_thumbnail(1234);
That will spit back:
HTML<img width="800" height="400"
src="https://example.com/test.png"
class="attachment-post-thumbnail size-post-thumbnail wp-post-image"
alt="This is some alt text."
decoding="async" loading="lazy" />"
If there's no alt, you'll see alt=""
.
Getting an attribute out of a scrap of HTML is simple. We're going to be naughty and pretend this is XML. Shhh! Don't tell the W3C!
PHP$xml = simplexml_load_string( get_the_post_thumbnail(1234) );
The alt text can be retrieved with:
PHP$alt = $xmlEl["alt"];
So anything where $xmlEl["alt"] == ""
is an image without alt text.
Finally, the code generates a link to the edit page of the post.
Khürt Williams said on photog.social:
@Edent this is pretty cool. I have nearly 7000 posts on WordPress going back 20 years. I think it’s too late to fix my laziness. I wish I could set the alt text using the title attribute from the EXIF.
More comments on Mastodon.