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." />';
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.