When you’re customizing your WordPress theme, you may often times find yourself in a situation where you need to display the featured image of a given post or another custom post type object. Sometimes, in those scenarios, you may need to use the wp_get_attachment_image function, which we’re going to explore today.
The wp_get_attachment_image Function Definition And Arguments
<?php
function wp_get_attachment_image(int $attachment_id, string|int[] $size = 'thumbnail', bool $icon = false, string|array $attr = '')
Here is the list of parameters that this function accepts:
- $attachment_id – the id of the attachment that needs to be displayed
- $size (optional) – Image size. Accepts any registered image size name, or an array of width and height values in pixels (in that order)
- $icon (optional) – whether the image should be treated as an icon.
- $attr (optional) – an array of attributes (src, alt, class, srcset, sizes, loading) that will be passed to the <img> html element
How To Use The wp_get_attachment_image Function
Let’s say we have a post object and we want to display its’ featured image. Here is how we would do it:
<?php
$post = get_post(123);
$attachmentId = get_post_thumbnail_id($post->ID);
// Display the attachment image
wp_get_attachment_image($attachmentId, 'thumbnail');
As you can see, we need to first get the ID of the attachment and then we display the image using the wp_get_attachment_image function.
This example shows how to use the function, but if you ever need to display the post thumbnail, there is a simpler way to do it:
<?php
$post = get_post(123);
// Display the attachment image
the_post_thumbnail($post->ID);
Functions Similar To wp_get_attachment_image Function
- wp_get_attachment_image_url – works similarly to wp_get_attachment_image function, but instead of returning the whole <img> html string, it only returns the URL of the image
- the_post_thumbnail – displays the post thumbnail
- wp_get_attachment_image_src – returns the array with the image source url, width, height, and a boolean value that indicates whether the image was resized or not
Wrapping Up
As you can see, the wp_get_attachment_image_url function can be handy in some rare situations, but it likely won’t be one of those functions you use every day.