Set Fallback for Background Image Alt Text

Something like this could be used in the context of wanting to attach descriptive content that would be hidden visually but available to screen readers for dynamic background images.

Example of how it’d be called:

<?php echo esc_attr( get_image_alt() ); ?>

Template tag itself:


function get_image_alt() {

	// Get ID of image.
	$image_id = get_post_thumbnail_id( $post_id );

	// Feed that ID to get the metadata.
	$alt_tag = get_post_meta( $image_id, '_wp_attachment_image_alt', true );

	// Set fallback to title if there isn't an 'alt' set on image.
	$alt = ( $alt_tag ) ? $alt_tag : get_the_title();

	return $alt;
}

Leave a Reply

Your email address will not be published.