# Name Links That Contain Only an Image Without Alt Text

> Gives links in your content whose only content is an image with empty alt text an accessible name, using the title of the page they point to, so screen readers no longer announce just the URL.

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

## Code

```php
add_filter( 'the_content', function ( $content ) {
    if ( false === stripos( $content, '<img' ) ) {
        return $content;
    }

    return preg_replace_callback( '#<a\b([^>]*)>\s*(<img\b[^>]*>)\s*</a>#i', function ( $m ) {
        if ( preg_match( '#\baria-label=#i', $m[1] ) || ( preg_match( '#\balt=(["\'])(.*?)\1#i', $m[2], $alt ) && '' !== trim( $alt[2] ) ) ) {
            return $m[0];
        }

        if ( ! preg_match( '#\bhref=(["\'])(.*?)\1#i', $m[1], $href ) ) {
            return $m[0];
        }

        $url     = html_entity_decode( $href[2] );
        $key     = 'wpide_linkname_' . md5( $url );
        $post_id = wp_cache_get( $key, 'wpide' );

        if ( false === $post_id ) {
            $post_id = (int) url_to_postid( $url );
            wp_cache_set( $key, $post_id, 'wpide', HOUR_IN_SECONDS );
        }

        if ( ! $post_id ) {
            return $m[0];
        }

        return '<a' . $m[1] . ' aria-label="' . esc_attr( wp_strip_all_tags( get_the_title( $post_id ) ) ) . '">' . $m[2] . '</a>';
    }, $content );
}, 20 );
```

## Notes

Only links to pages and posts on your own site can be named automatically; looked-up titles are cached.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Name Links That Contain Only an Image Without Alt Text" 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/
