Getting Library Image Attributes

I ran across a small problem the last days. I needed to obtain image attributes (title and alt) from WordPress library and send them to the img HTML tag. Once again, something that’s supposed to be simple, but took me some time.

Here’s how to obtain those elements using the image source link:

//FUNCTION TO GET IMAGE ID FROM SOURCE
function get_attachment_id_from_src ($image_src) {
global $wpdb;
$query = "SELECT ID FROM {$wpdb->posts} WHERE guid='$image_src'";
$id = $wpdb->get_var($query);
return $id;
}
$alt_text = get_post_meta(get_attachment_id_from_src($image_source), '_wp_attachment_image_alt', true);
$title_text = get_post(get_attachment_id_from_src($image_source))->post_title;
//OUTPUT THE IMAGE
echo '<img title=".$title_text." src=".$image_source." alt=".$alt_text." />';

The variable $image_source is the absolute path to the image that you want to get these attributes. This code works inside the loop and works for images that are inside your WordPress Media Library.

Web Designer
Web enthusiast since ever and full-time Web Designer since January 2012.
Delivering Premium WordPress Themes and freelance work to clients worldwide.

Leave a Comment

Your feedback is valuable for us. Your email will not be published.

Please wait...

Struggling to Monetize Your Instagram account?

Please check our new product: Spotsy! It is a free web service that allows any Instagram user to create a website in less than 5 minutes.
Learn More →