Skip to content

WordPress image sizes: find and stop the unused ones

If your WordPress uploads folder is too large, you can measure the disk each image size uses and disable image sizes the site never serves. You can then remove their old files without breaking the images already on your pages.

You run a WordPress site whose wp-content/uploads folder has grown far beyond what your photo library explains, and you want to stop the image sizes behind it. WordPress saves each upload as the original plus one resized copy for every registered size. A theme, WooCommerce and a couple of plugins can turn one photo into ten or more files, and most sites serve only some of them. Measure which sizes take the space, check which ones your pages actually request, and unregister the rest in a small must-use plugin. After a backup and a check that no post links to those files directly, wp media regenerate --delete-unknown removes the old files and updates each image’s metadata to match.

What you’ll accomplish

  • See every image size the site registers, with its dimensions and crop mode.
  • Know how many files and how much disk each size uses today.
  • Decide which sizes to keep from evidence: your theme’s code and 30 days of access logs.
  • Stop WordPress creating the unused sizes for every future upload.
  • Remove the old files of those sizes in an order that keeps images and srcset working.

Prerequisites

  • WordPress 5.3 or newer. That release added the 1536x1536 and 2048x2048 sizes, the -scaled copy, and the wp_get_missing_image_subsizes and big_image_size_threshold filters used below.
  • WP-CLI 2.11 or newer, which lets you run WordPress tasks from the shell. Run it over SSH as the site’s own user. Check with wp cli version. The --delete-unknown flag first shipped in 2.11.
  • At least 30 days of access logs. On cPanel, the current log sits in ~/access-logs/, and older months land in ~/logs/ when Raw Access has log archiving turned on.
  • Room for a full backup of wp-content/uploads and the database, stored off the server or on another disk.
  • Commands run from the WordPress root, the folder that holds wp-config.php, unless a step says otherwise.

How it works

When you upload a photo, WordPress keeps the original and writes one copy per registered size. The sizes come from three places. Core registers thumbnail, medium, medium_large and large (set under Settings → Media), plus 1536x1536 and 2048x2048. Your theme adds its own with add_image_size(). WooCommerce adds woocommerce_thumbnail, woocommerce_single and woocommerce_gallery_thumbnail to every upload, not only to product photos.

Each copy is named after the original with its pixel size added, such as harbour-1024x768.jpg. A hard-cropped size is cut to exact dimensions. A soft-cropped size is shrunk to fit inside a box and keeps its proportions, so its file names vary from image to image.

Big uploads get one more file. Any upload other than a PNG that is wider or taller than 2,560 pixels gets a -scaled copy at that limit, which WordPress serves as the “full” size. Never delete a -scaled file, because the attachment record points at it.

WordPress also records every copy in the attachment metadata, a database entry listing each size’s file name and dimensions. The srcset attribute, the list of alternative files a browser chooses from to fit the screen, is built from that record. It does not check the disk. That is why the order of work matters. Stop new copies first, then delete old ones only with a tool that updates the record at the same time. Files removed by hand leave the record listing them, and browsers request them and get 404 errors. The article on running wp media regenerate safely covers the files, the record and the original in more depth.

One 4032 by 3024 pixel upload, harbour.jpg, becomes a 2560 pixel scaled copy served as full size plus eight resized files. Five of them, the thumbnail, medium, medium_large, large and 1536x1536 sizes, are requested by pages. Three, the 2048x2048 copy and two theme sizes called mytheme-hero and mytheme-card, are rarely or never requested. An attachment metadata record lists all eight files, and srcset is built from it.

The figure leaves out the three WooCommerce sizes to stay readable.

SizeDefaultWho uses itUsually safe to stop?
thumbnail150 × 150, hard cropAdmin screens, many themesNo, the admin needs it
medium300 × 300, softAdmin previews, editor, srcsetNo
medium_large768 wide, softsrcset only, never offered in the editorRarely; it fills the gap between 300 and 1024
large1024 × 1024, softEditor, most themesNo
1536x15361536 × 1536, softsrcset on high-density screensOnly if logs show no requests
2048x20482048 × 2048, softsrcset on wide, high-density screensOften, on themes with a narrow content column
Theme and plugin sizesVariesWhatever template asks for it by nameYes, when no code asks and logs show none

Step-by-step

  1. List the registered sizes. Run the command that prints every size WordPress will generate:
wp media image-size

Example output:

+-------------------------------+-------+--------+------+-------+
| name                          | width | height | crop | ratio |
+-------------------------------+-------+--------+------+-------+
| full                          |       |        | N/A  | N/A   |
| 2048x2048                     | 2048  | 2048   | soft | N/A   |
| mytheme-hero                  | 1600  | 640    | hard | 5:2   |
| 1536x1536                     | 1536  | 1536   | soft | N/A   |
| large                         | 1024  | 1024   | soft | N/A   |
| medium_large                  | 768   | 0      | soft | N/A   |
| mytheme-card                  | 600   | 400    | hard | 3:2   |
| woocommerce_single            | 600   | 0      | soft | N/A   |
| medium                        | 300   | 300    | soft | N/A   |
| woocommerce_thumbnail         | 300   | 300    | hard | 1:1   |
| thumbnail                     | 150   | 150    | hard | 1:1   |
| woocommerce_gallery_thumbnail | 100   | 100    | hard | 1:1   |
+-------------------------------+-------+--------+------+-------+

The list is sorted by width, and full is the original or its -scaled copy, not a resized file. Every other row is one more file per upload. A height of 0 means “any height”. If the command fails with Error: This does not seem to be a WordPress installation, you are not in the WordPress root; add --path= followed by that folder.

  1. Measure the disk each size uses. Start with the totals, from inside the uploads folder:
cd wp-content/uploads
du -sh .
find . -type f -regextype posix-extended -regex '.*-[0-9]+x[0-9]+\.(jpe?g|png|gif|webp)$' -printf '%s\n' | awk '{s+=$1; n++} END {printf "sub-sizes: %d files, %.1f GB\n", n, s/1073741824}'
find . -type f -name '*-scaled.*' -printf '%s\n' | awk '{s+=$1; n++} END {printf "scaled: %d files, %.1f GB\n", n, s/1073741824}'
cd ../..

Example output:

41G	.
sub-sizes: 195259 files, 18.2 GB
scaled: 9870 files, 6.1 GB

The first count can include a few originals whose own names end in a pixel size. Next, split the sub-size total by size name. Save this as size-report.php in the WordPress root:

<?php
// Disk used by each image size name, read from attachment metadata.
$registered = wp_get_registered_image_subsizes();
$totals     = array();
$ids        = get_posts( array(
	'post_type'      => 'attachment',
	'post_mime_type' => 'image',
	'post_status'    => 'any',
	'posts_per_page' => -1,
	'fields'         => 'ids',
) );
foreach ( $ids as $id ) {
	$meta = wp_get_attachment_metadata( $id );
	$file = get_attached_file( $id );
	if ( empty( $meta['sizes'] ) || ! $file ) {
		continue;
	}
	foreach ( $meta['sizes'] as $name => $size ) {
		$path = dirname( $file ) . '/' . $size['file'];
		$totals[ $name ]['files'] = ( $totals[ $name ]['files'] ?? 0 ) + 1;
		$totals[ $name ]['bytes'] = ( $totals[ $name ]['bytes'] ?? 0 ) + ( is_file( $path ) ? filesize( $path ) : 0 );
	}
}
uasort( $totals, function ( $a, $b ) {
	return $b['bytes'] <=> $a['bytes'];
} );
foreach ( $totals as $name => $t ) {
	printf( "%-30s %7d files %9.1f MB  %s\n", $name, $t['files'], $t['bytes'] / 1048576, isset( $registered[ $name ] ) ? 'registered' : 'NOT registered' );
}

Then run it:

wp eval-file size-report.php

Example output:

2048x2048                        11902 files    6214.3 MB  registered
1536x1536                        12480 files    3871.9 MB  registered
mytheme-hero                     17955 files    2903.6 MB  registered
large                            18211 files    1702.4 MB  registered
oldtheme-slider                   6140 files    1288.2 MB  NOT registered
medium_large                     18260 files     742.8 MB  registered
woocommerce_single               18350 files     702.4 MB  registered
mytheme-card                     18377 files     611.0 MB  registered
woocommerce_thumbnail            18390 files     248.1 MB  registered
medium                           18390 files     214.7 MB  registered
thumbnail                        18402 files      96.5 MB  registered
woocommerce_gallery_thumbnail    18402 files      41.3 MB  registered

Large sizes have fewer files because WordPress skips a size bigger than the upload. A NOT registered row is left over from an old theme or a removed plugin: nothing creates those files any more, yet they still take space. Two sizes with identical dimensions share one file, so their rows count it twice. If every row shows 0.0 MB, the files live elsewhere, often in object storage through an offload plugin.

  1. Find which sizes your code asks for. Themes and plugins request a size by name. Search for each candidate from step 1, using the same names:
for s in 2048x2048 1536x1536 mytheme-hero mytheme-card; do
  echo "== $s"
  grep -rnF --include='*.php' --include='*.html' --include='*.json' -e "'$s'" -e "\"$s\"" wp-content/themes wp-content/plugins wp-content/mu-plugins 2>/dev/null | head -5
done

Example output:

== 2048x2048
== 1536x1536
== mytheme-hero
wp-content/themes/mytheme/functions.php:41:	add_image_size( 'mytheme-hero', 1600, 640, true );
== mytheme-card
wp-content/themes/mytheme/functions.php:42:	add_image_size( 'mytheme-card', 600, 400, true );

Here each theme size appears only on the line that registers it, so no template asks for it. Any other line is a real use: open the file and see whether that template is still active. Block themes store the chosen size in templates as "sizeSlug":"large", which the *.html and *.json patterns catch. Core sizes rarely show up by name, because srcset offers them automatically. The logs settle those.

  1. Count what visitors actually download. Your access log records every image file that browsers fetch. Count the requests that match each candidate size over at least 30 days. Replace example.com with your domain’s log name, and edit the four if lines to match your candidates:
zcat -f ~/access-logs/example.com* ~/logs/example.com*.gz 2>/dev/null \
  | grep -oE -- '-[0-9]+x[0-9]+\.(jpe?g|png|gif|webp)' \
  | awk -F'[-x.]' '{ w = $2 + 0; h = $3 + 0; long = (w > h ? w : h)
      if (long == 2048) c["2048x2048"]++
      if (long == 1536) c["1536x1536"]++
      if (w == 1600 && h == 640) c["mytheme-hero"]++
      if (w == 600 && h == 400) c["mytheme-card"]++ }
    END { n = split("2048x2048 1536x1536 mytheme-hero mytheme-card", s, " ")
      for (i = 1; i <= n; i++) printf "%-14s %d\n", s[i], c[s[i]] }'

Example output:

2048x2048      9
1536x1536      4127
mytheme-hero   0
mytheme-card   0

A hard-cropped size is matched on its exact dimensions. A soft size with a square box, such as 1536x1536, always has its longer side at the limit, so it is matched on that. Now decide. Treat a size as unused when no template asks for it in step 3 and its requests are close to zero. A cut-off of about one request a day (under 30 in 30 days) is a reasonable starting point, not a rule. A handful of hits usually comes from crawlers and old links, while real page traffic shows up in the hundreds or thousands. Raise or lower the cut-off to fit your traffic. With that cut-off, 2048x2048, mytheme-hero and mytheme-card qualify, and 1536x1536 stays. If every count is 0, the log path is wrong, or a content delivery network (CDN) answers image requests from its own cache. Run the same count on the CDN’s request logs instead.

  1. Stop generating the unused sizes. A must-use plugin is a PHP file in wp-content/mu-plugins/ that WordPress always loads and that nobody can deactivate from the admin. Create the folder if it does not exist, then save this as wp-content/mu-plugins/stop-unused-image-sizes.php, with your own names. The first list holds sizes to stop and clean up. The second, empty for now, holds sizes to stop while keeping their old files; step 7 tells you whether you need it.
<?php
/**
 * Plugin Name: Stop unused image sizes
 * Description: Keeps WordPress from generating image sizes this site never serves.
 */

// Stop generating these sizes and let step 8 delete their old files.
function sh_unused_image_sizes() {
	return array( '2048x2048', 'mytheme-hero', 'mytheme-card' );
}

// Stop generating these sizes but keep their old files, because posts link to them.
function sh_keep_file_sizes() {
	return array();
}

// Runs after core, the theme and WooCommerce have registered their sizes.
add_action( 'init', function () {
	foreach ( sh_unused_image_sizes() as $name ) {
		remove_image_size( $name );
	}
}, 100 );

// Blocks new copies of both lists, including sizes registered later than init.
$sh_drop_sizes = function ( $sizes ) {
	return array_diff_key( $sizes, array_flip( array_merge( sh_unused_image_sizes(), sh_keep_file_sizes() ) ) );
};
add_filter( 'intermediate_image_sizes_advanced', $sh_drop_sizes );
add_filter( 'wp_get_missing_image_subsizes', $sh_drop_sizes );

remove_image_size() unregisters a size, so the cleanup in step 8 treats its files as unknown and deletes them. Sizes in the second list stay registered, so the cleanup leaves their files alone. The intermediate_image_sizes_advanced filter covers new uploads. The wp_get_missing_image_subsizes filter covers the path that fills in missing sizes, which ignores the first filter. If you put this in a theme’s functions.php instead, the next theme update undoes it.

The four core sizes thumbnail, medium, medium_large and large are settings rather than registered names, so remove_image_size() cannot touch them. WordPress skips any of them whose width and height are both 0. Keep thumbnail, medium and large, which the admin and editor use. To stop medium_large, whose height is already 0, run wp option update medium_large_size_w 0. It prints Success: Updated 'medium_large_size_w' option.

Optionally, lower the -scaled limit to 2,048 pixels by adding this line to the same file:

add_filter( 'big_image_size_threshold', function () { return 2048; } );

New big uploads then get a 2,048-pixel -scaled copy, and srcset offers it as the widest choice, so dropping 2048x2048 costs no sharpness. Returning false turns scaling off, and pages showing the full size would then serve the original camera file. Existing -scaled files stay as they are.

  1. Confirm new uploads skip those sizes. Run wp media image-size again. The names in your first list should be gone from the table; names in the second list stay. Then import any photo at least 2,560 pixels wide and list the sizes it received:
wp media import ~/test-photo.jpg --porcelain
wp eval 'echo implode( " ", array_keys( wp_get_attachment_metadata( 31877 )["sizes"] ) ), PHP_EOL;'
wp post delete 31877 --force

Replace 31877 with the ID that the first command prints. Example output:

31877
medium large thumbnail medium_large 1536x1536 woocommerce_thumbnail woocommerce_single woocommerce_gallery_thumbnail
Success: Deleted post 31877.

If a name from either list still appears in the second line, or a first-list name is still in the table, see Troubleshooting before going further.

  1. Back up, then check whether posts link to the files. Step 8 deletes files, and nothing in WordPress can bring them back. Take a backup and check that it reads before you go on:
wp db export ~/backup-before-sizes.sql
tar -czf ~/uploads-before-sizes.tar.gz wp-content/uploads
tar -tzf ~/uploads-before-sizes.tar.gz | wc -l

Expect Success: Exported to '/home/user/backup-before-sizes.sql'., no output from the first tar, and a file count from the second at least as large as the files in uploads. An error such as Unexpected EOF in archive means the archive is damaged, often from a full disk; fix that before going further. Then copy both files off the server, because a backup on the same disk is lost with it. When you insert an image into a post, WordPress writes the chosen file’s address into the post content. Builders such as Elementor store it in post metadata instead. Search both for each size you plan to clean:

P=$(wp db prefix)
wp db query "SELECT post_type, COUNT(*) AS posts FROM ${P}posts WHERE post_content REGEXP '-2048x[0-9]+[.]|x2048[.]|-1600x640[.]|-600x400[.]' GROUP BY post_type"
wp db query "SELECT meta_key, COUNT(*) AS hits FROM ${P}postmeta WHERE meta_key <> '_wp_attachment_metadata' AND meta_value REGEXP '-2048x[0-9]+[.]|x2048[.]|-1600x640[.]|-600x400[.]' GROUP BY meta_key"

No output from both means no post links to those files, and the cleanup is safe. A row such as post with a count of 14 means posts embed them. Deleting those files would leave a broken image in each of those posts. Move each matching size from the first list in the plugin to the second. WordPress stops making new copies, and step 8 leaves the existing files where the posts need them. The x2048 pattern also matches unrelated names such as logo-512x2048.png; open a few matches before you decide.

  1. Remove the old files with WP-CLI. The --delete-unknown flag deletes the files of every size that is no longer registered and removes them from each image’s metadata. It resizes nothing. Do not start it until the backup in step 7 has been checked and copied off the server. Try two attachments first. List two image IDs, then run the cleanup on them:
wp post list --post_type=attachment --post_mime_type=image --posts_per_page=2 --format=ids
wp media regenerate 4410 4411 --delete-unknown

Use the two IDs the first command prints in place of 4410 4411. Example output:

4411 4410
Found 2 images to regenerate.
1/2 Deleted unknown image sizes for "Harbour at dusk" (ID 4410).
2/2 Deleted unknown image sizes for "Dock crane" (ID 4411).
Success: Regenerated 2 of 2 images.

Load a page that shows one of them and confirm the image displays. If it does not, stop and restore the two images from the backup. Otherwise clean the whole library, then refill anything removed by accident:

wp media regenerate --delete-unknown --yes
wp media regenerate --only-missing --yes

The first command also clears NOT registered leftovers such as oldtheme-slider. The second command matters. If an old size shared its dimensions with a size you kept, they shared one file, and the first command deleted it. --only-missing rebuilds only images that have a missing size file, and deletes nothing. Most lines end in No thumbnail regeneration needed for followed by the image. A plain run without either flag would delete and re-encode every size of every image. That run has its own risks, covered in running wp media regenerate safely, and you do not need it here.

Validate it works

Compare the folder with the figure from step 2 and run the report again:

du -sh wp-content/uploads
wp eval-file size-report.php

The total should drop by roughly the megabytes those sizes showed. Their rows should be gone, and so should the NOT registered ones. Next, prove that one image’s srcset lists only files that exist:

wp eval 'echo wp_get_attachment_image( 4410, "large" ), PHP_EOL;' | grep -oE 'https?://[^ ",]+' | sort -u | while read -r u; do printf '%s %s\n' "$(curl -s -o /dev/null -w '%{http_code}' "$u")" "$u"; done

Example output:

200 https://example.com/wp-content/uploads/2024/06/harbour-1024x768.jpg
200 https://example.com/wp-content/uploads/2024/06/harbour-1536x1152.jpg
200 https://example.com/wp-content/uploads/2024/06/harbour-300x225.jpg
200 https://example.com/wp-content/uploads/2024/06/harbour-768x576.jpg

Every line should start with 200. A 404 means a file vanished while the record still lists it; see Troubleshooting. Finally, open a few pages and posts in a private browser window, purge any page cache and CDN first, and confirm the images display.

Troubleshooting

A removed size still appears in wp media image-size. The plugin that adds it registers the size after init priority 100, or the must-use file sits in a subfolder, which WordPress does not load. Keep the file directly in wp-content/mu-plugins/. For a late size, change 'init' to 'wp_loaded' in the plugin. The filters already block new copies, but --delete-unknown keeps a registered size’s files.

Images vanished from some posts after cleanup. Those posts embed a cleaned size’s file directly. Restore each missing file from the backup to the same path, running this from the WordPress root with the path the post uses:

tar -xzf ~/uploads-before-sizes.tar.gz wp-content/uploads/2024/06/harbour-2048x1536.jpg

No output means the file is back. Posts use the plain file address, so the image returns at once. Move that size to the second list in the plugin so a later cleanup leaves it alone.

A WooCommerce size keeps coming back. WooCommerce creates a missing woocommerce_* file when a template asks for it, and queues a background rebuild after theme or Customizer changes. If a size returns this way, your store uses it, so keep it registered.

WP-CLI reports unknown --delete-unknown parameter. WP-CLI is older than 2.11. Run wp cli update, or ask your host to update it, then confirm with wp cli version.

The report or cleanup runs out of memory. A very large library can exceed PHP’s limit. Run the cleanup in ID batches through xargs, as described in running wp media regenerate safely.

When this is the wrong approach

If a CDN or image service resizes images on request, most local sizes are dead weight. Point the theme at the service and keep only the sizes the admin needs.

If the sub-sizes are small next to the originals, the space is in camera files. Lower big_image_size_threshold and compress instead; never delete originals, since WordPress needs them to make any size later.

On a multisite network, each site has its own uploads folder and metadata. Run the report and the cleanup per site with --url=.

A library under a few gigabytes rarely repays this work. Stopping the sizes (step 5) is quick and safe; the cleanup can wait until disk gets tight.

Running WordPress that earns real money deserves an operator — Stack Harbor runs that stack under Enterprise WordPress; book an infrastructure consult.