Get a single specific image from Wordpress Media Library

Viewed 47913

I've uploaded images to Wordpress Media Library.

I understand that I can view am image then get the URL for that specific image and then use the img html tag to display this on the page.

This however doesn't get the alt, title, caption and description of the image.

The img is not attached to a post or page field and so i assume you cannot use the Get Attachment function etc.

The reason I want to use a function instead of writing out a static img html code is so that they are cached better and easier to maintain with all data for the image been updated in the Media Library instead of having to edit html code which is not idea for the end user.

thank you in advance.

4 Answers

So many complicated and to my opinion wrong answers while the answer is very straight forward:

<?php
$url_to_my_attachment = "http://example.com/wp-content/uploads/image.png";

$attachment_id = attachment_url_to_postid($url_to_my_attachment);

print wp_get_attachment_image($attachment_id);

For more information have a look at wp_get_attachment_image

Note: this renders a "responsive image" where the alt attribute contains the alt data of the attachment. Thus this answer doesn't completely satisfy the OP's request which also demands to include the title, description and caption fields. See the accepted answer or other answers on how to include these other fields.

Related