Get image alt attribute just by image URL

Is there a possible way to get the alt text from the media file by just knowing the URL? For example, if the path to my image is /bc/wp-content/uploads/placeholder-image.png is there a way (just by using that URL) to get the alt text of that image. I know you usually need the ID and such, trying to find a way around this.

PHP

<img src="https://wordpress.stackexchange.com/bc/wp-content/uploads/placeholder-image.png" alt="<?php /* do something */ ?>" />

2 Answers
2

Using the function found here, you could add this to your functions.php

// retrieves the attachment ID from the file URL
function pippin_get_image_id($image_url) {
    global $wpdb;
    $attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url )); 
    return $attachment[0]; 
}

But to use it, you need the full image URL.

$img_url = get_bloginfo('url') . "https://wordpress.stackexchange.com/bc/wp-content/uploads/placeholder-image.png";

if ( $img_id = pippin_get_image_id($img_url) ) {
    // Using wp_get_attachment_image should return your alt text added in the WordPress admin.
    echo wp_get_attachment_image( $img_id, 'full' );
} else {
    // Fallback in case it's not found.
    echo '<img src="' . $img_url . '" alt="" />';
}

Leave a Comment