# Use Image Captions as Alt Text When Alt Is Empty

> For image blocks that have a caption but no alternative text, uses the caption text as the alt attribute, so the image is not announced as unlabeled.

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

## Code

```php
add_filter( 'render_block_core/image', function ( $html ) {
    if ( false === stripos( $html, '<figcaption' ) || ! class_exists( 'WP_HTML_Tag_Processor' ) ) {
        return $html;
    }

    if ( ! preg_match( '#<figcaption[^>]*>(.*?)</figcaption>#is', $html, $m ) ) {
        return $html;
    }

    $caption = trim( wp_strip_all_tags( $m[1] ) );
    $tags    = new WP_HTML_Tag_Processor( $html );

    if ( $caption && $tags->next_tag( 'img' ) && '' === trim( (string) $tags->get_attribute( 'alt' ) ) ) {
        $tags->set_attribute( 'alt', wp_html_excerpt( $caption, 150, '' ) );
        return $tags->get_updated_html();
    }

    return $html;
} );
```

## Notes

A caption and alt text ideally say different things; treat this as a fallback and write real alt text where you can.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Use Image Captions as Alt Text When Alt Is Empty" 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/
