I found some short snippets of code to set the alt text of images - when the image is uploaded, added to the editor and used as a post thumbnail. I simply combined them into one file.
By default WordPress does not set the Alternative Text (aka ‘alt’ text) of uploaded images. The image title is set to the name of the uploaded file. Alt text is useful for screen readers when the user cannot see the image. I wanted to find a way to automatically populate the alt text when an image is uploaded.
A quick web search returned:
- snippet that set the title, caption and description of an image as it is uploaded (by Francisco Ruiz)
- a plugin that generates the alt when an image is added to the editor (by Dan)
- a snippet that sets the alt attribute of the post thumbnail markup to the post title (by Bojan Petrovic)
I have combined these three pieces of code into a single plugin file. The only change I made was that I moved a tiny portion of Francisco’s code to a separate function and call that function from Dan’s code. This code removed hyphens, underscores & extra spaces from the image title and then capitalised the first letter of each word. For example: this-is-the-image-title becomes This Is The Image Title.