Skip to content
14+ years building on WordPress / Replies in under 5 hours
WordPress 10 min read · Updated November 2026

How to Use wp_get_attachment_image() in WordPress Templates

Photo of Ajay Khandal
Ajay Khandal
WordPress Developer
On this page
Key takeaways

wp_get_attachment_image( $id, $size, $icon, $attr ) returns a complete <img> tag for a media library item, with width, height, alt, srcset and sizes filled in. You must echo it. Since WordPress 6.3, core also sets loading, fetchpriority and decoding, and any value you pass in $attr overrides them. For a bare URL, use wp_get_attachment_image_url().

  • An unregistered size name quietly serves the full original file, often 2,560px wide.
  • Pass an attachment ID. A resized image URL won't resolve back to an ID.
  • Since WordPress 6.3, core sets loading, fetchpriority and decoding, and $attr values override them.
  • Use wp_get_attachment_image_url() only when you need a bare URL.

wp_get_attachment_image() is the function I use every time a custom theme prints an image from the media library. You give it an attachment ID and a size, and it returns a finished <img> tag with width, height, alt, srcset and sizes already filled in.

The examples below come from the theme that runs this site (WordPress 7.1), including the HTML it actually produces. Where a detail depends on a WordPress version, I link the official reference so you can check it against your own install. If you are building a theme from the ground up, the custom theme walkthrough covers the template files these calls live in.

What does wp_get_attachment_image() return?

It returns an HTML string: a complete <img> element for the attachment, or an empty string when the ID is missing or the file has no image to show. It never prints anything by itself, so you must echo the result. The default size is 'thumbnail', which is 150 by 150 pixels on a fresh install.

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

Here is what each parameter does, per the official function reference:

Parameter What it takes Notes
$attachment_id The attachment post ID (integer) An ID, never a URL or a filename
$size A registered size name, or an array of width and height Defaults to 'thumbnail'
$icon true or false When true, non-image files such as audio return a mime-type icon
$attr An array of extra HTML attributes Your values override the defaults WordPress builds

Before output, WordPress runs every attribute through esc_attr() and applies the wp_get_attachment_image_attributes filter. That means you can pass plain strings in $attr without escaping them yourself.

Where do you get the attachment ID?

The attachment ID usually comes from one of three places: the post’s featured image through get_post_thumbnail_id(), an ACF image field set to return an ID, or a number you saved in post meta. Check that the value is not empty before you call the function, because a missing ID returns an empty string with no warning.

From the featured image

This is how the homepage template on this site gets the ID of the hero photo, which is the front page’s featured image:

// front-page.php, the theme running ajaykhandal.com
$ak_home_photo = get_post_thumbnail_id( get_the_ID() );

From an ACF image field

Set the field’s return format to Image ID and the field gives you an integer you can pass straight in. With the Image Array format, read the ID key. If you are still choosing a custom fields plugin, I compared the options in ACF Pro vs Meta Box vs Pods.

// Return format: Image ID
$image_id = get_field( 'hero_image' );
if ( $image_id ) {
    echo wp_get_attachment_image( $image_id, 'large' );
}

// Return format: Image Array
$image = get_field( 'hero_image' );
if ( $image ) {
    echo wp_get_attachment_image( $image['ID'], 'large' );
}

// Gallery field (return format: Image ID), one img per item
foreach ( (array) get_field( 'product_gallery' ) as $gallery_id ) {
    echo wp_get_attachment_image( $gallery_id, 'medium' );
}

From post meta

Post meta comes back as a string, so cast it to an integer to match the function signature:

$image_id = (int) get_post_meta( get_the_ID(), 'banner_image_id', true );
if ( $image_id ) {
    echo wp_get_attachment_image( $image_id, 'large' );
}

Which image sizes can you pass to wp_get_attachment_image()?

You can pass any registered size name, including the core sizes 'thumbnail', 'medium', 'medium_large', 'large' and 'full', or a custom size added with add_image_size(). You can also pass an array such as [ 800, 450 ], and WordPress picks the closest generated file that fits.

Size name Default dimensions Behaviour
'thumbnail' 150 × 150 px Hard cropped to a square
'medium' Up to 300 × 300 px Scaled, proportions kept
'medium_large' 768 px wide Scaled, no height limit
'large' Up to 1024 × 1024 px Scaled, proportions kept
'full' The stored original No resizing

The first three sizes can be changed in Settings, Media. Changing them only affects new uploads, so run wp media regenerate in WP-CLI or a regenerate plugin to rebuild older files.

Two details trip people up. First, 'full' is often a resized copy: since WordPress 5.3, uploads wider or taller than 2,560 pixels are scaled down on upload and the scaled file becomes the largest available size (see the big_image_size_threshold hook). Second, a size name WordPress cannot find does not trigger an error. image_downsize() falls back to the original image and its stored dimensions, so a typo in the size name can quietly send a multi-megabyte file to phones.

With an array, image_get_intermediate_size() looks for an exact match first, then the smallest generated size that is at least as large in both directions and has the same aspect ratio. No new file is created. If you need a fixed crop, register it:

// functions.php
add_image_size( 'card', 640, 360, true ); // 640 x 360, hard cropped

// template
echo wp_get_attachment_image( $image_id, 'card' );

How do you add a class, alt text or other attributes?

Pass an associative array as the fourth argument. Each key becomes an attribute on the <img> tag, and any key you set replaces the value WordPress would have used. Passing 'class' replaces the default attachment-{size} size-{size} classes, so include them yourself if your CSS relies on them.

echo wp_get_attachment_image( $image_id, 'large', false, array(
    'class' => 'attachment-large size-large card__img',
    'alt'   => get_the_title(),
    'style' => 'width:100%;height:auto;',
) );

Alt text comes from the media library entry by default. Override it when the context changes the meaning, and pass an empty string for purely decorative images so screen readers skip them. WordPress adds no title attribute; add one through $attr only when you have a reason to. Page builder users can do the same in the editor, as shown in adding a title tag to an image in Elementor.

Escaping your own values first, as in 'alt' => esc_attr( $text ), is redundant because the function already escapes every attribute. It does no harm, and the homepage template on this site still has one of those calls.

How does WordPress decide loading, fetchpriority and decoding?

Since WordPress 6.3, wp_get_attachment_image() asks wp_get_loading_optimization_attributes() which loading hints to add. The first large image it expects near the top of the page gets fetchpriority="high", other early images skip lazy loading, and later images get loading="lazy". Most images also get decoding="async". Anything you set in $attr wins.

The rules, from the 6.3 and 6.4 core notes and the function reference:

  • Lazy loading by default arrived in WordPress 5.5, and decoding="async" in 6.1.
  • The first three media elements in the main content area skip lazy loading. That number comes from wp_omit_loading_attr_threshold(), which changed from 1 to 3 in 6.3.
  • Core never returns fetchpriority="high" and loading="lazy" together. If you set both, it raises a warning.
  • Passing 'loading' => false removes the attribute completely.
  • Since 7.0, a fetchpriority of low or auto that you pass is kept, and core adds no lazy loading to that image.

Sources: Image performance enhancements in WordPress 6.3, Image loading optimization enhancements in 6.4 and wp_omit_loading_attr_threshold().

For the hero image, I set the hints explicitly so the result never depends on core’s guess about page position. This is the call in this site’s front-page.php, with the alt line shortened:

echo wp_get_attachment_image( $ak_home_photo, 'large', false, array(
    'alt'           => 'Ajay Khandal, freelance WordPress developer',
    'loading'       => 'eager',
    'fetchpriority' => 'high',
) );

The single post template does the opposite and lets core decide. It calls the_post_thumbnail( 'large', array( 'style' => '...' ) ) with no loading hints, and WordPress still adds fetchpriority="high" and leaves out loading, because the featured image is the first image in the main loop. The hero image is usually the Largest Contentful Paint element, so lazy loading it would delay that metric; the Core Web Vitals guide explains how LCP is measured.

What does the output look like on a live site?

The homepage call above produces this tag on ajaykhandal.com today. WordPress filled in the dimensions, the alt text, four srcset candidates and a sizes rule from one function call. The only attributes I wrote by hand were alt, loading and fetchpriority, while decoding came from core.

<img width="765" height="1024"
  src="https://cdn.ajaykhandal.com/2026/07/hero-ajay-2-765x1024.png"
  class="attachment-large size-large"
  alt="Ajay Khandal, freelance WordPress developer"
  loading="eager" fetchpriority="high" decoding="async"
  srcset="https://cdn.ajaykhandal.com/2026/07/hero-ajay-2-765x1024.png 765w,
          https://cdn.ajaykhandal.com/2026/07/hero-ajay-2-224x300.png 224w,
          https://cdn.ajaykhandal.com/2026/07/hero-ajay-2-768x1029.png 768w,
          https://cdn.ajaykhandal.com/2026/07/hero-ajay-2.png 896w"
  sizes="(max-width: 765px) 100vw, 765px" />

The blog cards further down the same page come from get_the_post_thumbnail( $p->ID, 'medium' ). Those images sit below the fold, so core gives them loading="lazy" and starts their sizes value with auto:

sizes="auto, (max-width: 300px) 100vw, 300px"

That auto keyword was added in WordPress 6.7 for lazy-loaded images. It lets the browser use the image’s real rendered width to choose a file from srcset. The 6.7 core note explains the behaviour and the wp_img_tag_add_auto_sizes filter that turns it off.

Use wp_get_attachment_image() when you are printing an image and want WordPress to handle srcset, sizes and loading hints. Use the URL functions only when you need a bare address, for example for a CSS background, an og:image tag or JSON-LD. The featured image helpers are wrappers around the same function.

Function Returns Use it when
wp_get_attachment_image() Full <img> string, or empty string You have an attachment ID and are printing an image
get_the_post_thumbnail() Full <img> string, or empty string You want a post’s featured image; default size is 'post-thumbnail'
the_post_thumbnail() Prints the featured image You are inside the loop and want to echo directly
wp_get_attachment_image_url() URL string, or false CSS backgrounds, meta tags, JavaScript
wp_get_attachment_image_src() Array of URL, width, height and an is-resized flag, or false You need the dimensions along with the URL
get_the_post_thumbnail_url() URL string, or false You need only the featured image’s address

On this site, get_the_post_thumbnail_url( null, 'large' ) supplies the image property in the Article schema, and the case study archive uses it for card backgrounds. Every visible <img> goes through wp_get_attachment_image() or one of its featured image wrappers. get_the_post_thumbnail() calls wp_get_attachment_image() internally and adds the post_thumbnail_size and post_thumbnail_html filters on top.

$bg = wp_get_attachment_image_url( $image_id, 'large' );
if ( $bg ) {
    printf( '<div class="hero" style="background-image:url(%s)"></div>', esc_url( $bg ) );
}

Templates often print the title next to the image; getting the title in a WordPress template covers that pair of functions.

Why does wp_get_attachment_image() show nothing?

A blank result almost always means the function returned an empty string or the return value was never printed. The function does not throw errors or log warnings, so work through the causes in order. Most cases are fixed by the first two checks: echo the result and confirm the ID is a real attachment.

  1. Check that you used echo. The function returns HTML and prints nothing on its own.
  2. Print the ID with var_dump( $image_id ). A value of 0, false or an empty string means the source field is empty.
  3. Confirm you passed an ID. If you only have a URL, attachment_url_to_postid( $url ) looks up the ID with a database query. It matches the main file path, so a resized URL such as photo-300x200.jpg returns 0.
  4. Open Media in wp-admin and check that the attachment still exists and is an image. For non-image files, pass true as the third argument to get an icon.
  5. Check the ACF field’s return format. A field set to return a URL gives you a string that this function cannot use.

If the image prints but looks wrong, check the size name first. An unregistered name silently returns the original file, which is the most common reason a small card loads a 2,560 pixel image.

I build and maintain custom WordPress themes where these calls are set per template, so the hero loads first and everything below it waits its turn.

Frequently asked questions

get_the_post_thumbnail() looks up a post's featured image ID and then calls wp_get_attachment_image() with it, adding the post_thumbnail_size and post_thumbnail_html filters. Its default size is 'post-thumbnail' instead of 'thumbnail'. Use it for featured images, and use wp_get_attachment_image() when the ID comes from ACF, post meta or a gallery.

Call wp_get_attachment_image_url( $attachment_id, 'large' ). It returns the URL of that size as a string, or false if the attachment has no image. If you also need the width and height, use wp_get_attachment_image_src(), which returns an array of URL, width, height and a flag for whether the file is a resized copy.

No. wp_get_attachment_image() runs every attribute value through esc_attr() before building the tag, so plain strings are safe. Wrapping a value in esc_attr() yourself is redundant but harmless. You still need esc_url() when you print a URL from wp_get_attachment_image_url() inside your own markup.

Yes, if the image is the first large element visitors see, which usually makes it the Largest Contentful Paint element. Pass 'loading' => 'eager' (or false) and 'fetchpriority' => 'high' in $attr. Never combine fetchpriority high with loading lazy; WordPress 6.3 and later raise a warning when both are set.

Since WordPress 5.3, any upload larger than 2,560 pixels in width or height is scaled down when it is uploaded, and the scaled copy becomes the largest available size, so 'full' returns that copy. You can change or disable the limit with the big_image_size_threshold filter.

Photo of Ajay Khandal

Written by Ajay Khandal

I'm a freelance WordPress developer with 14+ years of experience building, fixing, and speeding up sites for businesses, agencies, and store owners across the US, UK, Europe, and Australia. I specialize in custom themes, WooCommerce, and performance, the kind of work that shows up as faster load times and fewer support tickets. You work directly with me, and replies typically arrive within 5 hours.

Work with me →