You have uploaded an image in Media Library of WordPress either from the Dashboard ( Dashboard > Media ) or from the Customizer ( Image Custom Control ) and want to show the image in your theme. There are many ways to go about it. The only thing we have at our disposal is the URL of the uploaded image (although we can manually get the ID of the attachment Image from the Media Library but that’s not a developer’s way of doing things!). We can use this URL to output an <img> tag which shows the the image on the front end. Let’s see how to get the Image Tag from it’s URL.

There are 2 major ways togo about it. We can either manually create an <img> tag and use the URL in the src attribute. Consider the code below –

<img src={URL of the image}>

No doubt we’ll get the image to be shown at the front-end but the tag is without any other attributes like title, srcset, classes and others. These attributes are necessary to increase the visibility of the image and make it more SEO Friendly and Optimized. Here is a list of all the attributes that are present in the <img> tag –

  • src
  • class
  • alt
  • srcset
  • sizes
  • loading

We can manually enter these attributes to form the tag. That would be too much work. Fortunately, WordPress provides a couple of nifty functions to get the complete <img> tag of the uploaded images.

In particular, we are going to use 2 functions – attachment_url_to_postid and wp_get_attachment_image. The wp_get_attachment_image functions returns the complete HTML <img> tag using the attachment ID. In order to get the attachment ID from the URL of the image, we use the attachment_url_to_postid function. This function takes the URL of an attachment and returns its ID. Consider the code below –

$image_id = attachment_url_to_postid({the URL of Image}); //ID of the Attachment

$image = wp_get_attachment_image( $image_id ); //The complete <img> tag

The $image variable stores the <img> tag, complete in all aspects with all the attributes present and ready to be used in the front-end.

Leave a Reply

Your email address will not be published. Required fields are marked *