Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

Code

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 add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.