# Use Media Library Alt Text for Images Missing It in Posts

> When an image in a post has an empty alt attribute but its Media Library entry has alt text, the library text is used on the page, fixing older posts without editing them.

- Type: PHP
- Runs: Frontend only
- Category: [Media](https://wpide.com/library/category/media/)
- Tags: alt-text, accessibility, images
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/media-fill-alt-from-library-on-output/

## Code

```php
add_filter( 'wp_content_img_tag', function ( $image, $context, $attachment_id ) {
    if ( ! $attachment_id || ! preg_match( '/\salt=(["\'])\s*\1/', $image ) ) {
        return $image;
    }

    $alt = trim( (string) get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) );
    if ( '' === $alt ) {
        return $image;
    }

    return preg_replace( '/\salt=(["\'])\s*\1/', ' alt="' . esc_attr( $alt ) . '"', $image, 1 );
}, 10, 3 );
```

## Notes

Images deliberately left with empty alt text are filled too if the library has a description; clear the library alt text for decorative images.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Use Media Library Alt Text for Images Missing It in Posts" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
