# Use the Post Title as Alt Text for Featured Images Without One

> When a featured image has no alternative text, outputs the post title as its alt attribute in themes and blocks, instead of leaving it empty.

- Type: PHP
- Runs: Frontend only
- Category: [Accessibility](https://wpide.com/library/category/accessibility/)
- Tags: alt-text, featured-image, images
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/a11y-featured-image-alt-fallback/

## Code

```php
add_filter( 'post_thumbnail_html', function ( $html, $post_id ) {
    if ( ! $html || ! class_exists( 'WP_HTML_Tag_Processor' ) ) {
        return $html;
    }

    $tags = new WP_HTML_Tag_Processor( $html );

    if ( $tags->next_tag( 'img' ) && '' === trim( (string) $tags->get_attribute( 'alt' ) ) ) {
        $tags->set_attribute( 'alt', wp_strip_all_tags( get_the_title( $post_id ) ) );
        return $tags->get_updated_html();
    }

    return $html;
}, 10, 2 );
```

## Notes

Only affects images shown as a post's featured image; images that already have alt text keep it.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Use the Post Title as Alt Text for Featured Images Without One" 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/
