Function for Guaranteed Alt Text

Laura Kressin

For developers working with accessibility compliance, alt text for media is important.  In the WordPress CMS, images are already built with an “Alt Text” field, that both content creators and developers can utilize to make their site accessible for users of all abilities.

Unfortunately, the user entering content and uploading images does not often utilize this field.  In order to prevent empty alt text in image tags, we created a function to grab image fields in succession, until some sort of text or description was found.

function ada_image_alt($imageObject, $fallbackText='Image Alternative Text'){
    if( $imageObject['alt'] != '' ){
        $alt = $imageObject['alt'];
    }elseif( $imageObject['title'] != '' ){
        $alt = $imageObject['title'];
    }elseif( $imageObject['caption'] != '' ){
        $alt = $imageObject['caption'];
    }elseif( $imageObject['description'] != '' ){
        $alt = $imageObject['description'];
        $alt = $fallbackText;
    return $alt;

This function grabs the image fields in this order, until some sort of input is found: “Alt Text”, “Title”, “Caption”, “Description”. If all else fails, set the $fallbackText.

These fields can be reordered, depending on want the CMS user will commonly input, and what information will be most useful to the end user.

In your html, echo your new php function:

<img src="<?php print $image['url'];?>" alt="<?php echo ada_image_alt($image)?>" />

And there you are

You're welcome

Last updated by on .

What Are Your Thoughts?

Your email address will not be published. Required fields are marked *