wp-content » themes » functions.php » Automatically add featured image Alt Text from post title

Automatically add featured image Alt Text from post title

The following code snippet will automatically generate Alt Text for all featured images from the Post Title.

function featured_image_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', 'featured_image_alt_text', 10, 4);

If you are looking for more settings, check the SEO Friendly Images plugin.

See also  How to hide a plugin from the WordPress plugins list 🙈

Was this post helpful?

Leave a Comment

I enjoy constructive responses and professional comments to my posts, and invite anyone to comment or link to my site.

Recommended