Last active
November 22, 2019 04:10
-
-
Save acafourek/b5d6e8a0bc39feb0a1f970af1403016d to your computer and use it in GitHub Desktop.
Fallback logic for image alt text
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Fallback logic for image alt tags | |
* Ref: https://wordpress.stackexchange.com/a/175179/10269 | |
* Filter each get_post_meta request - if it's a request for image alt tag, we make sure it exists or supply a fallback. | |
* Fallback is saved to the image to reduce overhead on future requests | |
* To get really fancy, consider future use of AWS Rekognition APIs or https://cloud.google.com/vision/ for otehr SEO-specific image APIs | |
*/ | |
function air_image_alt_tag_fallback($metadata, $object_id, $meta_key, $single){ | |
if(!$meta_key || $meta_key !== "_wp_attachment_image_alt") | |
return $metadata; | |
//avoid a loop | |
remove_filter( 'get_post_metadata', 'air_image_alt_tag_fallback', 100 ); | |
$alt_text = get_post_meta( $object_id, '_wp_attachment_image_alt', TRUE ); | |
if(!$alt_text || empty($alt_text)){ | |
//fallback to other data | |
$image = get_post($object_id); | |
/** | |
* Fallback steps: | |
* Alt Text | |
* Caption | |
* Description | |
* Title | |
*/ | |
if(!empty($image->post_excerpt)){ | |
//Caption | |
$alt_text = $image->post_excerpt; | |
}elseif(!empty($image->post_content)){ | |
//Description | |
$alt_text = $image->post_content; | |
}elseif(!empty($image->post_title)){ | |
//Title -- will always have a value because WP assigns on upload based on filename | |
$alt_text = $image->post_title; | |
} | |
//save back to the image | |
update_post_meta( $object_id, '_wp_attachment_image_alt',$alt_text); | |
} | |
add_filter('get_post_metadata', 'air_image_alt_tag_fallback', 100, 4); | |
// Return original if the check does not pass | |
return $alt_text; | |
} | |
add_filter( 'get_post_metadata', 'air_image_alt_tag_fallback', 100, 4 ); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment