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 –

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 –

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.

And That’s it! Just a 2 line snippet. Honestly, I’ve seen people doing all sort of fancy things to build the <img> tag. WordPress provides us with pre-built solution for getting the image tag from attachment Image’s URL in WordPress.

Hope you got to learn something from this mini article. Please let me know if there’s a better way of doing this or it could be made better.

Leave a Reply

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