Monday, 26-09-2022

wp_get_attachment_image_src() – a WordPress Function to Returns Array of Image Data

wp_get_attachment_image_src() is a WordPress Function retrieve an image to represent an attachment. In practical use wp_get_attachment_image_src is very useful for displaying an attached image if you don’t need image meta or the alt attribute.


File: wp-includes/media.php



$attachment_id (int) (Required) Image attachment ID.
$size (string|int[]) (Optional) Image size. Accepts any registered image size name, or an array of width and height values in pixels (in that order). Default value: ‘thumbnail’
$icon (bool) (Optional) Whether the image should fall back to a mime type icon. Default value: false.

By default, wp_get_attachment_image_src return an array of image with 4 values url, width, height, is_intermediateIf there is no image, the function returns false.


Get URL, width, the height of image with attachment id 18:

To get the original size URL of an image in the function wp_get_attachment_image_src use:

Size option:  If you want to get the URL of an attachment in custom size, you can declare $size according to array(width, height)

The example below used wp_get_attachment_image_src to takes the thumbnail size image and the custom size is 640x400

Please note that if the thumbnail size 640×400 does not exist, wp_get_attachment_image_src will not working and return false.

In some cases, the array $size will not working in wp_get_attachment_image_src function. The reason is that $size does not exist, so you have to add that $size support by use adds image size function in your functions.php file like this.

Then you can use this code to get the image URL with the defined size

Another example of getting the attachment URL for the medium-sized image

Alt text: wp_get_attachment_image_src function will not return an image attachment’s Alt text. If you want to get alt text, you should use wp_get_attachment_image() a function instead.

Bonus: In case you want to get an attachment ID from an image URL, please use this function:


About Author

Leave A Reply