Auto add ALT to WordPress featured images

I found this bit of PHP code that worked fine. What it does is that if your featured images in WordPress have empty ALT tags, then it will use the WordPress post title to fill them.

Add the following code to your theme functions.php file. And not the WordPress functions.php file…

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);

I got the code from this guy: https://letswp.io/post-title-alt-text-featured-image/

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.