When a theme or page builder stores an image as a plain URL (e.g. in a theme options field or an ACF text field), you lose access to the attachment’s alt text and title stored in the Media Library. The functions below let you look up an attachment by its URL and retrieve those attributes properly.
Problem: You have an image URL stored in a custom field and need to retrieve its alt text and title attribute from the WordPress media library — without knowing the attachment ID.
Solution: Convert the URL to an attachment ID using attachment_url_to_postid(), then retrieve the alt text with get_post_meta($id, '_wp_attachment_image_alt', true) and the title with get_the_title($id).
Step 1. Add the following helper functions to functions.php:
<?php
/**
* Get the attachment ID for a given image URL.
* Returns the ID (int) on success, or false if not found.
*/
function get_attachment_id_by_url( $url ) {
global $wpdb;
$url = esc_url_raw( $url );
$id = $wpdb->get_var(
$wpdb->prepare(
"SELECT ID FROM $wpdb->posts WHERE guid = %s LIMIT 1",
$url
)
);
return $id ? (int) $id : false;
}
/**
* Get the alt text and title for an attachment.
* Returns an array with 'alt' and 'title' keys.
*/
function get_attachment_alt_and_title( $attachment_id ) {
return [
'alt' => get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ),
'title' => get_the_title( $attachment_id ),
];
}
Step 2. Use them together at the point where you render the image:
<?php
$image_url = get_option( 'my_logo_url' ); // or any URL source
$image_id = get_attachment_id_by_url( $image_url );
if ( $image_id ) {
$image_data = get_attachment_alt_and_title( $image_id );
printf(
'<img src="%s" alt="%s" title="%s" class="logo">',
esc_url( $image_url ),
esc_attr( $image_data['alt'] ),
esc_attr( $image_data['title'] )
);
} else {
// Fallback: render without alt/title
printf( '<img src="%s" alt="" class="logo">', esc_url( $image_url ) );
}
Alternatively, if you have the attachment ID available, you can use WordPress's built-in function to render a fully accessible image tag in one call:
<?php
if ( $image_id ) {
echo wp_get_attachment_image( $image_id, 'full', false, [ 'class' => 'logo' ] );
}
NOTE: The GUID-based lookup works reliably only when the image URL has not changed since the attachment was inserted. If images have been migrated, resized by a CDN, or had their domain changed, the GUID will no longer match the current URL. In those cases, use attachment_url_to_postid() instead, which handles common URL variations automatically.