Google
  • Home
  • WordPress Themes
  • Blog
  • Support Forum
  • Get In Touch
  • Theme Tryout
  • Home
  • WordPress Themes
  • Blog
  • Support Forum
  • Get In Touch
  • Theme Tryout

Getting Library Image Attributes

WordPress
-
No comments
-
Posted by Pirenko

I ran across a small problem the last days. I needed to obtain image attributes (title and alt) from WordPress library and pass 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.

Tags
Advanced
Coding
WordPress
← PREVIOUS POST
vt_resize.php - image_resize deprecated
NEXT POST →
Disabling Wordpress Comments
Interested in my latest WordPress Themes?
Shout
Blogging WordPress Theme
Hook
Superior WordPress Theme
Verve
High-Style WordPress Theme

Pirenko

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.
Cancel Reply

Please wait...
Submit Comment

About Us

Over the last years we created 16 WP Themes and performed hundreds of customizations on Themes and Plugins. We also built a large number of websites for clients all over the world.

Quick Access

  • Home
  • WordPress Themes
  • Blog
  • Support Forum
  • Get In Touch
  • Theme Tryout

Elsewhere

  • Spotsy – Monetize Your Instagram
  • Our Privacy Policy
  • Themeforest
  • Twitter
  • Facebook
  • YouTube

Mailing List

Sign up for our newsletter and be notified about new theme releases. By using this form you agree with our Privacy Policy.

This website and all our theme demos are proudly hosted at Siteground.
This website was built with Hook WordPress Theme.
Buy Hook for WordPress →

Getting Library Image Attributes | Pirenko Studio

Struggling to Monetize Your Instagram account?

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