Find WordPress featured images with no alt text

Created on November 12, 2023 at 11:36 am

WordPress ORG allows you to set a featured image – called a "thumbnail" in the API ORG . 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 ORG 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.

Paste this into wp shell to get a list.

foreach (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 PERSON (). "/wp-admin/post.php?post=" . $post->ID . "&action=edit " . $post->post_title . "

"; } }

To get the image element of the featured image, use get_the_post_thumbnail(1234); That will spit back:

<img width="800" height="400" src=" PERSON /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!

$xml = simplexml_load_string( get_the_post_thumbnail(1234) );

The alt text can be retrieved with:

$alt = $ xmlEl["alt GPE "];

So anything where $xmlEl["alt"] == "" is an image without alt text.

Finally, the code generates a link to the edit page of the post.

Connecting to Connected... Page load complete