Skip to content

Instantly share code, notes, and snippets.

@RemcoWessels
Last active January 21, 2022 16:41
Show Gist options
  • Save RemcoWessels/6a76ef59af8d39b58ba43a398c85b363 to your computer and use it in GitHub Desktop.
Save RemcoWessels/6a76ef59af8d39b58ba43a398c85b363 to your computer and use it in GitHub Desktop.
WordPress function; As it is important for a11y (accessibility) that images got an ALT text this function adds, on upload, the IPTC description from the image to the "Alternative Text" field within WordPress.
/* Automatically set an image Alt-Text on upload */
add_action( 'add_attachment', 'kreks__add_alt_text_from_image_IPTC_on_upload' );
function kreks__add_alt_text_from_image_IPTC_on_upload( $post_ID ) {
// Check if uploaded file is an image, else do nothing
if ( wp_attachment_is_image( $post_ID ) ) {
$postMeta = get_post_meta($post_ID);
$uploads = wp_get_upload_dir();
$imgURL = $uploads['basedir'] . "/" . $postMeta['_wp_attached_file']['0'];
$size = getimagesize( $imgURL, $imageInfo );
$iptc = iptcparse($imageInfo['APP13']);
$description = $iptc["2#120"][0];
// Set the image Alt-Text
update_post_meta( $post_ID, '_wp_attachment_image_alt', $description );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment