When I ran a Sitebulb SEO audit on this site, I was bummed by the fact that it said images are missing alt texts. Given that I meticulously add such a text to every image I add to articles, that was intriguing. As it turns out, the scapegoat was the featured image. Denes provides those and when writing content, I don’t concern myself with the article’s image. Even if I did, copy-pasting the post title to be the alt text would be a robotic task in itself. Backlogging that or committing to yet another step of article creation is something I wanted to avoid. Not to mention titles may change in the future. Therefore, I propose automatically adding the post title as the alt text of the featured image, unless it exists already.
The snippet is really simple. First, I hook into the swiss army knife of metadata-getting, get_{$meta_type}_metadata
which is really useful in various ways. For instance, the meta key doesn’t even need to exist and that brings possibilities like creating programmatic metadata. I limit the function to the featured image and prevent an infinite loop in the condition. Before getting a title, I respect the existing alt text, if any.
function lwp_37481_featured_alt_text($metadata, $object_id, $meta_key, $single) {
if(isset($meta_key) && $meta_key == '_wp_attachment_image_alt'
&& get_post_thumbnail_id() == $object_id
&& $single === true
){
$original_value = get_post_meta(
$object_id, '_wp_attachment_image_alt', false
);
if(empty($original_value)){
return get_the_title();
}
}
return $metadata;
}
add_filter('get_post_metadata', 'lwp_37481_featured_alt_text', 10, 4);
Add that code snippet to your WordPress, and voila. Now you (and Google) will see the post title as alt text on your featured images. There is no longer a need to manually set the alt text. Yay!
Initially, I thought this was going to be an Elementor snippet, but it should work well outside of that ecosystem. It’ll act wherever your theme shows a post with its featured image (including post boxes on a blog home page, archives, single post, etc). At the end of the day, it simulates having that alt text filled out by you. Any system that respects that (would be considered a best practice) will be fooled by my approach. 🙂
Why have post title as alt text?
The SEO benefit may be slim, but all the small bits matter. Especially so if the only image in your article is the featured image, why not do everything in your power for a better on-page SEO? If you ignore this, they’ll just exist without an alt text, and perhaps you are missing out on a small opportunity.
Comments are closed.