Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 68 ยท Classic Themes and the Template Hierarchy

Images, Thumbnails and Media

Understand how WordPress stores uploads, creates image sizes, adds srcset and lazy loading, and how to register sizes and print featured images in a theme.

Images are usually the heaviest part of a web page, and WordPress does a lot of work on your behalf. When someone uploads a photo, WordPress saves the original, creates several smaller copies, records everything in the database, and later prints <img> tags with responsive attributes. Understanding that pipeline lets you pick the right size in a theme, avoid blurry or oversized images and keep pages fast.

This lesson explains the media library and attachments, image sizes and add_image_size(), featured images with the_post_thumbnail(), the srcset and sizes attributes that core generates, lazy loading and fetchpriority, and alt text. The runnable example is a plain-PHP stand-in for the srcset calculation, because WordPress cannot run on this site. Code blocks with WordPress functions are read-only.

You should know how template tags work from Template Parts and Template Tags.

Uploads are posts

Every file in the media library is a row in the wp_posts table with the post type attachment and the status inherit. Its details live in post meta:

  • _wp_attached_file holds the path relative to the uploads folder, such as 2026/05/trail.jpg.
  • _wp_attachment_metadata holds a serialized array with the width, height and every generated size.
  • _wp_attachment_image_alt holds the alt text.

Files are stored in wp-content/uploads/YYYY/MM/ by default. Because an attachment is a post, you can query it with WP_Query, attach it to a parent post, and use functions such as get_the_title( $attachment_id ). A featured image (post thumbnail) is simply a post meta entry, _thumbnail_id, on the parent post that stores the attachment ID.

flowchart TD
    U["Upload trail.jpg<br/>(2400 x 1600)"] --> O["Original saved in<br/>uploads/2026/05"]
    U --> S["Sub-sizes generated<br/>thumbnail, medium, large, ..."]
    O --> DB["wp_posts row<br/>post_type = attachment"]
    S --> M["_wp_attachment_metadata<br/>lists every size"]
    DB --> P["Post meta:<br/>_wp_attached_file<br/>_wp_attachment_image_alt"]

One upload becomes one post, several files, and a few meta entries.

Image sizes

WordPress generates a fixed set of sizes at upload time. The defaults (thumbnail, medium and large can be changed in Settings > Media) are:

Size name Default box Crop
thumbnail 150 x 150 hard crop
medium 300 x 300 no
medium_large 768 wide no
large 1024 x 1024 no
1536x1536 1536 x 1536 no
2048x2048 2048 x 2048 no

"No crop" means the image is scaled down to fit inside the box while keeping its proportions. A 2400 x 1600 photo in the large box becomes 1024 x 683, because the width is the limiting side. "Hard crop" means the image is cut to the exact dimensions.

Very large uploads are also scaled down: files with a side above 2560 pixels are saved as a scaled copy, and the untouched original is kept separately. You can change the threshold with the big_image_size_threshold filter.

Adding your own sizes

Register extra sizes in after_setup_theme:

PHP
function mytheme_images(): void {
    add_theme_support( 'post-thumbnails' );

    set_post_thumbnail_size( 1200, 630, true );   // default size for the_post_thumbnail()
    add_image_size( 'card', 640, 400, true );       // hard-cropped card image
    add_image_size( 'hero', 1600, 0 );              // 1600 wide, any height
}
add_action( 'after_setup_theme', 'mytheme_images' );

Pass a height of 0 to leave it unlimited. Each size is created for every future upload, so add only what you need; ten unused sizes mean ten extra files per image. Existing uploads are not resized when you add a size. A tool such as WP-CLI's wp media regenerate creates the missing files for old images.

add_theme_support( 'post-thumbnails' ) enables the featured image box. In a template, use:

PHP
if ( has_post_thumbnail() ) {
    the_post_thumbnail( 'card', [ 'class' => 'card__image' ] );
}

the_post_thumbnail() prints a full <img> tag. The sibling functions return values instead of printing them: get_the_post_thumbnail() returns the tag, get_the_post_thumbnail_url() returns only the URL (handy for a CSS background or Open Graph tag), and wp_get_attachment_image( $id, 'card' ) works with any attachment ID, not only the featured one.

A typical tag looks like this:

HTML
<img width="640" height="400"
     src="/wp-content/uploads/2026/05/trail-640x400.jpg"
     class="card__image wp-post-image"
     alt="A mountain trail at dawn"
     decoding="async"
     srcset="/wp-content/uploads/2026/05/trail-640x400.jpg 640w, ..."
     sizes="(max-width: 640px) 100vw, 640px"
     loading="lazy">

Core added each of these attributes for a reason, covered next.

srcset and sizes, generated for you

A phone with a narrow screen should not download a 1600 pixel image. The srcset attribute lists several files with their widths, and the sizes attribute tells the browser how wide the image will be displayed. The browser then picks the best file.

WordPress builds srcset from the sub-sizes recorded in _wp_attachment_metadata. Only sizes with the same aspect ratio as the requested image are included, since a hard-cropped thumbnail would show a different part of the photo. By default, sources wider than 2048 pixels are left out (the max_srcset_image_width filter changes this), and a srcset needs at least two entries to be printed.

If you do not supply a sizes value, core uses a generic one that says "full width on small screens, the image's own width on larger screens", which has this shape:

TEXT
(max-width: 1024px) 100vw, 1024px

That default is a guess. If your image is displayed in a three-column grid, the real display width is much smaller, and the browser downloads more than it needs. Pass a better sizes through the attributes array, or use the wp_calculate_image_sizes filter:

PHP
the_post_thumbnail( 'card', [ 'sizes' => '(min-width: 900px) 33vw, 100vw' ] );

A srcset calculator

This stand-in repeats the logic in a simplified form: it computes each registered size for an original image, drops sizes with a different aspect ratio, drops anything above the width limit, and prints the attributes.

PHP srcset and sizes calculator (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The 150 pixel hard-cropped thumbnail and the 640 x 400 card (a 16:10 crop of a 3:2 photo) are dropped because their shapes differ, and the width limit would drop anything wider than 2048 pixels (no registered size here exceeds it, and this model leaves out the original file). In real WordPress the exact decisions depend on the stored metadata and active filters, so treat this as a model of the rule, not a copy of core.

Lazy loading, decoding and fetchpriority

Core now adds performance attributes automatically:

  • loading="lazy" (since WordPress 5.5) tells the browser not to download an image until it nears the viewport. This is great for images far down the page.
  • decoding="async" lets the browser decode the image off the main thread.
  • fetchpriority="high" (since WordPress 6.3) marks the image likely to be the largest on-screen element so it is fetched early, and core skips lazy loading for it.

Lazy loading an image that is visible on the first screen makes the page slower, because the browser waits to discover it. Core tries to detect above-the-fold images and leave them eager. When you know better, override the attributes yourself:

PHP
the_post_thumbnail( 'hero', [
    'loading'       => 'eager',
    'fetchpriority' => 'high',
] );

Treat this as a tool for your hero image only, since marking everything high priority makes none of it stand out.

Alt text

The alt attribute is not optional. It is read by screen readers, shown when an image fails to load, and used by search engines. Editors enter it in the media library, and WordPress stores it in _wp_attachment_image_alt. Good alt text describes the purpose of the image in context ("A mountain trail at dawn"), not the file name ("IMG_2231.jpg"). For purely decorative images the alt should be present but empty (alt=""), so assistive technology skips them. You can override it when printing:

PHP
echo wp_get_attachment_image( $id, 'card', false, [ 'alt' => esc_attr( $custom_alt ) ] );

Never leave out the alt attribute entirely; an image with no alt attribute at all is read out by some screen readers as its file name.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is a media library file in the WordPress database?

    Attachments are posts with post_type attachment. Details such as the file path, sizes and alt text are stored as post meta.
  2. 2. You add a new image size with add_image_size(). What happens to images uploaded last year?

    Sizes are generated at upload time. Old uploads need their files regenerated, for example with wp media regenerate.
  3. 3. Why does core leave a hard-cropped thumbnail out of srcset?

    srcset entries must show the same picture at different widths, so only sizes with the same aspect ratio are included.
  4. 4. Which attribute helps the browser fetch the main hero image early?

    fetchpriority="high" raises the download priority of the image that is likely the largest element on screen. Lazy loading would delay it.
  5. 5. What alt value is right for a purely decorative image?

    An empty alt tells assistive technology to skip the image. A missing alt attribute may be read out as the file name.

Summary

  • Uploads are attachment posts; the file path, generated sizes and alt text live in post meta, and a featured image is the _thumbnail_id meta of the parent post.
  • Sizes are generated at upload time. Register your own with add_image_size() and regenerate old files when you add one.
  • the_post_thumbnail() prints the tag, and the get_ variants return the tag or the URL.
  • Core builds srcset from same-ratio sizes and a generic sizes value. Provide a better sizes for grids and sidebars.
  • loading="lazy", decoding="async" and fetchpriority are added for you; override them for the hero image.
  • Always write meaningful alt text, or an empty alt for decorative images.

Next, learn how to customize someone else's theme safely in Child Themes.