# Fill Missing Alt Text From the File Name

> When an image is uploaded without alt text, creates one from its title (based on the file name), replacing dashes and underscores with spaces.

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

## Code

```php
add_action( 'add_attachment', function ( $attachment_id ) {
    if ( ! wp_attachment_is_image( $attachment_id ) ) {
        return;
    }

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

    $alt = trim( preg_replace( '/[\s_-]+/', ' ', (string) get_the_title( $attachment_id ) ) );

    if ( '' !== $alt ) {
        update_post_meta( $attachment_id, '_wp_attachment_image_alt', sanitize_text_field( ucfirst( $alt ) ) );
    }
} );
```

## Notes

Generated alt text is only as good as the file name. Review it for important images.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Fill Missing Alt Text From the File Name" 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/
