Header Text - Use thewp_get_attachment_image Function in WordPress

The wp_get_attachment_image function in WordPress is a useful tool to display images attached to your posts or pages. It’s specifically designed to retrieve an image in HTML format so that it’s ready to be displayed on your website. This function is great when you want to add pictures in Custom Themes or Plugins, making it easier to manage images directly from the WordPress Media Library.

Using wp_get_attachment_image is important for developers who want more control over how images are presented on their site. Instead of manually adding HTML for every image, this function automates the process and ensures WordPress handles image attributes essential for website SEO and responsive design.

In this tutorial, we show you how the function works, explain its parameters, and give examples of the function being used. By the end, you’ll know everything about adding dynamic images to your WordPress projects.

What is wp_get_attachment_image Function?

As explained above, the wp_get_attachment_image function is a built-in WordPress function used to retrieve and display an image already uploaded and attached to a WordPress post or page. It generates the necessary HTML <img> tag for an image, including attributes like size, alt text, and CSS classes, making it easy for developers to include pictures in their Themes or Plugins.

When you upload an image to a post or page in WordPress, it is stored in the Media Library and assigned an attachment ID. This attachment ID is a unique identifier for the image. The function uses this ID to locate the image and retrieve its URL, size, and other related information. Based on the parameters you pass, the function outputs a <img> tag that displays the image.

For example, you provide the attachment ID and specify a size (such as ‘thumbnail’ or ‘large’). The function then retrieves the image of that size and inserts it into your site’s HTML, ready to be displayed in a post, page, or custom template. It also ensures WordPress applies the correct sizes and attributes, which are important for design and SEO.

echo wp_get_attachment_image( $attachment_id, 'medium' );

In this example, the function grabs the image with the specified attachment ID and outputs its medium-sized version, complete with the necessary HTML.

Parameters of the wp_get_attachment_image Function

The wp_get_attachment_image function helps you get an HTML <img> tag for an image attachment.

wp_get_attachment_image( int $attachment_id,
string|int[] $size = 'medium',
bool $icon = false,
string|array $attr = '' );

To use this function, you must provide at least one required parameter — the image attachment ID, which is the unique ID for the image. By default, the function shows the full-sized image without extra HTML attributes or customizations.

You can also include optional parameters to customize how the image looks. The wp_get_attachment_image function uses multiple parameters to control how the image is displayed. Let’s break down each one below:

$attachment_id (Required): This is the ID of the image you want to display. It is necessary and must be a valid attachment ID from your WordPress Media Library. Its default value is None; this must always be provided. If you don’t give a correct ID or issue an incorrect value, the function won’t display anything because it cannot locate the image.

$size (Optional): This defines the image size to display. You can use preset sizes like ‘thumbnail’, ‘medium’, ‘large’ or ‘full’, or custom sizes you defined in your WordPress theme. Here, ‘thumbnail’ is the default size if no value is provided. However, if an incorrect value is specified (like a non-existent size), WordPress defaults to the thumbnail size or may display the full-sized image.

$icon (Optional): This controls whether to display an attachment icon instead of the image itself. It is rarely used because it’s mostly for non-image attachments like PDFs. Its default value is false, meaning the actual image is shown by default. If the value is true, it will show the attachment’s icon instead of the picture.

$attr (Optional attributes like class, alt, srcset, sizes, loading): This allows you to add extra HTML attributes to the image tag, such as a CSS class, alt text, or loading attributes for lazy loading. By default, it’s set to an empty array, which means no extra attributes are added. You can pass an array of key-value pairs below,

['class' => 'custom-class', 'alt' => 'Image description', 'loading' => 'lazy']

to add the following attributes:

  • class: It manages the CSS class of the image tag. You can add several classes by separating them with spaces.
  • alt: Defines the image’s alt text. This attribute is important for accessibility and helps with WordPress SEO.
  • srcset: Thisallows you to provide different image sources with varying resolutions, sizes, or aspect ratios. The browser automatically selects the best one based on a device’s screen resolution.
  • sizes: Works alongside the srcset attribute, specifying the image size to be displayed depending on the available space on the page.
  • loading: Controls how the image is loaded. For instance, the default value is set to lazy, enabling lazy loading.
  • decoding: Specifies how the browser should decode the image. Options include async for asynchronous decoding, sync for synchronous decoding, or auto.

Remember, if you don’t provide the values for additional attributes, the function won’t add any extras. However, if incorrect values are passed, the function will ignore them, and no additional attributes will be applied to the image.

Now that you know what the wp_get_attachment_image function is and its parameters, let’s show you how to use it with various code examples.

How to use the wp_get_attachment_image Function

Before we dive into the uses of the wp_get_attachment_image function, it’s important to know where you can use it. Use this function in your theme’s single.php or page.php files to display images, such as featured images.

If you have custom templates for specific post types or pages, use this function to display images. Furthermore, images (like logos) can be necessary in the header or footer. The function can also be used for those images.

Also, if you’re building a custom plugin to dynamically display images, such as for a gallery or slideshow, use the wp_get_attachment_image function to retrieve and show necessary images based on attachment IDs.

Additionally, you can use wp_get_attachment_image inside the loop to display images for each post. For example, we used the following code in the Neve theme’s single.php file to show a thumbnail of the featured image:

if ( have_posts() ) {
                while ( have_posts() ) {
                                the_post();
                                echo wp_get_attachment_image( get_post_thumbnail_id(), 'thumbnail' );
                                get_template_part( 'template-parts/content', 'single' );
                }
} else {
                get_template_part( 'template-parts/content', 'none' );
}

Let’s explore a few more cases where you can use this function in WordPress.

Output a Ready-To-Use HTML Image

The easiest way to test the wp_get_attachment_image() function is by passing an image attachment ID.

echo wp_get_attachment_image(282);

In this example, since no image size is specified, the function displays the full-sized version of the image with attachment ID 282. Here, the resulting HTML output looks like this, as if an alt text is already set:

<img width="150" height="150" src="https://www.yourdomain.online/wp-content/uploads/2024/10/laptop-image-150x150.jpg" class="attachment-thumbnail size-thumbnail" alt="laptop-image" decoding="async">

By default, the image is shown as 150 pixels wide and 150 pixels tall, but the actual size can differ based on the original image dimensions.

Use the wp_get_attachment_image Function - Output Ready-to-use HTML Image

You will notice the difference in the image width and height if you use the default parameters of the function as follows:

echo wp_get_attachment_image(282, 'full' );

Now, the corresponding HTML will look like this:

<img width="1280" height="826" src="https://www.yourdomain.online/wp-content/uploads/2024/10/laptop-image.jpg" class="attachment-full size-full" alt="laptop-image" decoding="async" fetchpriority="high" srcset="https://www.yourdomain.online/wp-content/uploads/2024/10/laptop-image.jpg 1280w, https://www.yourdomain.online/wp-content/uploads/2024/10/laptop-image-300x194.jpg 300w, https://www.yourdomain.online/wp-content/uploads/2024/10/laptop-image-1024x661.jpg 1024w, https://www.yourdomain.online/wp-content/uploads/2024/10/laptop-image-768x496.jpg 768w" sizes="(max-width: 1280px) 100vw, 1280px">

Display a Post Thumbnail

First, use the has_post_thumbnail function to check if the post has a featured image. If true, then use get_post_thumbnail_id to retrieve the featured image’s ID. This ID is necessary to fetch the image. Once you have the ID, use the wp_get_attachment_image function to display the image on the site. Here’s a simple example of how this works:

if ( has_post_thumbnail() ) {
    $thumbnail_id = get_post_thumbnail_id();
    echo wp_get_attachment_image( $thumbnail_id, 'full' );
}
Use the wp_get_attachment_image Function - Display Post Thumbnail

Important:

You may replace the full image size with any registered image size.

Block Text: Maximize your website’s potential with WordPress Hosting from Hosted.com. Revamp your site’s functionality with custom WordPress features and extensive customization options.

Show all Images Associated with a Post

You may want to display all images attached to a post. In that case, use get_attached_media() to retrieve the media files and loop through them. Here’s the example code:

$attachments = get_attached_media( 'image', get_the_ID());
foreach ( $attachments as $attachment ) {
    echo wp_get_attachment_image( $attachment->ID, 'thumbnail' );
}

This code retrieves all image attachments associated with the current post using get_attached_media(). It then loops through each attachment and displays a thumbnail-sized version of each image using the wp_get_attachment_image() function. In this example, get_the_ID() is used to retrieve the current post’s ID.

Use the wp_get_attachment_image Function - Display All Images of a Post

Get Image Attachment ID from a Custom Field & Display It

If the image is stored as a custom field, you can get the attachment ID by accessing the custom field value as follows:

$image_url =  get_post_meta(get_the_ID(), 'your_custom_image_field_key', true);
$attachment_id = attachment_url_to_postid( $image_url );
if ( $attachment_id ) {
    echo wp_get_attachment_image( $attachment_id, 'medium' );
}

In the above example, ensure you replace your_custom_image_field_key with the actual key of your meta field. This code retrieves an image URL from a custom field (your_custom_image_field_key), converts the URL to its corresponding attachment ID using attachment_url_to_postid(), and then displays the image in medium size using the wp_get_attachment_image() function if a valid attachment ID is found.

Use the wp_get_attachment_image Function - Display Image from a Custom Field

However, if you want to display any uploaded image and need the image ID, you can use a custom query or manually get the ID from the Media Library. To do this, go to Media Library in your WordPress dashboard. Then, select the image you want. In the URL of the “image editor” page, you’ll see something like this:

https://www.yourdomain.online/wp-admin/upload.php?item=60

Here, 60 is the attachment ID.

Specify Class, Alt, & Title Attributes

Add custom attributes like class, alt, and title to improve accessibility and SEO. You can do this by passing an array of attributes to the function as follows:

$attr = array(
    'class' => 'custom-class',
    'alt'   => 'Custom Alt Text',
    'title' => 'Custom Title',
   
);
echo wp_get_attachment_image( $attachment_id, 'medium', false, $attr );

This example sets a custom class, alt text, and title for the image, which is important for user experience and Search Engine Optimization.

Manually Construct the Image Markup

In some cases, you may want more control over how the image is displayed, which means manually constructing the HTML <img> tag. This is where wp_get_attachment_image_src() comes in handy. This function gives you the image URL, width, and height, allowing you to customize image output on your site.

Let’s say you want to display a medium-sized image but want to add custom classes or extra HTML attributes. Here’s how you can do it:

$attachment_id = 282; // Replace with your image attachment ID
$image_data = wp_get_attachment_image_src( $attachment_id, 'medium' ); // Get the medium size
if ( $image_data ) {
    $image_url = $image_data[0]; // The image URL
    $image_width = $image_data[1]; // The image width
    $image_height = $image_data[2]; // The image height

    // Manually construct the <img> tag
    echo '<img src="' . esc_url( $image_url ) . '" width="' . esc_attr( $image_width ) . '" height="' . esc_attr( $image_height ) . '" class="custom-class" alt="Custom Alt Text" loading="lazy">';
}

By manually constructing the image markup, you have more flexibility to style or optimize the image based on your specific needs.

Strip Banner Text - Improve your website's features with dependable WordPress Hosting. [Get started]

KEY TAKEAWAYS

  1. The wp_get_attachment_image function lets you display images stored in the WordPress Media Library.
  2. It requires an image ID, and you can customize the size, icon, and attributes like alt text and class.
  3. The function helps you automate how images are displayed, making it useful for custom Themes and Plugins.
  4. You can use the WordPress get image by ID feature to load and display images.
  5. Adding custom attributes enhances SEO and accessibility and improves page performance with lazy loading.

FAQs

What does the wp_get_attachment_image function do?

The function retrieves an image from the WordPress Media Library and outputs it in HTML format, making it ready to display on your website.

What is $attachment_id in the function?

This is the ID of the image you want to display. This parameter is required for the function to work.

How do I change the image size using this function?

You can change the image size by using the $size parameter. Common options include ‘thumbnail’, ‘medium’, and ‘full’, or you can set custom dimensions.

Can I add attributes like class or alt to the image?

Yes. You can use the $attr parameter to add attributes like class, alt, and title. You can also use loading for better performance and SEO.

Can I display multiple images with this function?

Yes. You can display multiple images using a loop with the get_attached_media function to retrieve every image attached to a post and display them one at a time.

How to Install WordPress Themes: A Beginner’s Guide

How to Fix the WordPress 500 Internal Server Error

WordPress Recovery Mode: Everything You Need to Know

How to Password Protect A WordPress Site – The Ultimate Guide

How To Migrate A WordPress Site To A New Host