wp_get_image_alttext()
Retrieves alternative text from XMP metadata in an image file.
Looks for the Iptc4xmpCore:AltTextAccessibility field. When it contains multiple language variants, it selects the first suitable one in this order:
- an exact match for the site locale, for example
fr_FR. - a match for the first two characters of the locale, for example
ru. - the
x-defaultlanguage variant.
When an image is uploaded, WordPress uses this text to populate the Alt field in the Media Library.
The function retrieves text directly from the file, not from the _wp_attachment_image_alt meta-field. It does not save the found text to the database.
To retrieve Alt text saved for an attachment in the Media Library, use get_post_meta():
$alt_text = get_post_meta( $attachment_id, '_wp_attachment_image_alt', true );
On the front end, the function file may need to be included manually:
require_once ABSPATH . `wp-admin/includes/image.php`.
No Hooks.
Returns
string.
string- the found alternative text.''- if the file could not be read, XMP metadata is missing or corrupt, the required field was not found, or no suitable language variant exists.
Usage
wp_get_image_alttext( $file );
- $file(string) (required)
- The image file path. The function reads the entire file.
Examples
#1 Retrieve embedded image Alt text
require_once ABSPATH . 'wp-admin/includes/image.php';
$file = wp_get_original_image_path( 123 );
if ( $file ) {
$alt_text = wp_get_image_alttext( $file );
echo esc_html( $alt_text );
}Changelog
| Since 7.0.0 | Introduced. |