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.

PHP 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 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 PHP$xml = simplexml_load_string( get_the_post_thumbnail(1234) );

The alt text can be retrieved with:

PHP 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.


Share this post on…

  • Mastodon
  • Facebook
  • LinkedIn
  • BlueSky
  • Threads
  • Reddit
  • HackerNews
  • Lobsters
  • WhatsApp
  • Telegram

One thought on “Find WordPress featured images with no alt text”

What are your reckons?

All comments are moderated and may not be published immediately. Your email address will not be published.

Allowed HTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <p> <pre> <br> <img src="" alt="" title="" srcset="">