The command you almost certainly want is wp media regenerate --only-missing --yes. --only-missing is the flag that saves you: it skips every attachment whose sub-sizes are already on disk, and it turns off the deletion pass that a plain run does first. A bare wp media regenerate --yes deletes each attachment’s existing sub-size files before writing new ones, which on a large library means hours of CPU, tens of gigabytes of writes, hundreds of thousands of inodes, and thumbnail URLs that start returning 404 to anyone who hardcoded them. This guide covers the flags that actually exist, how to price the job in disk and hours before you commit to it, how to drive a 100,000-attachment run without making the site unusable, and how to recover when it dies halfway.
What you’ll accomplish
- Read the real synopsis and know what each flag does, including the one that silently implies another.
- Do the disk and inode arithmetic before you start, because every registered size multiplies per attachment.
- Scope the run down to the smallest thing that fixes your problem: specific IDs, an ID range, one
--image_size, or--only-missing. - Drive a 100k-attachment job in batches under
tmuxornohup, throttled withniceandioniceso the site stays responsive. - Recover from the four ways these runs actually end badly: memory, a full disk, a killed process, and originals that no longer exist.
Prerequisites
- WP-CLI 2.x on the server with SSH access. Check with
wp cli version. Themediacommand ships with WP-CLI itself; nothing to install. - WordPress 5.3 or newer. That release introduced
wp_create_image_subsizes(),wp_get_registered_image_subsizes(), thebig_image_size_thresholdfilter and-scaledoriginals — the model this guide assumes. - Either Imagick or GD available to PHP. WordPress prefers Imagick when it is present and supports the MIME type, and falls back to GD.
- Write access to
wp-content/uploads/from the account WP-CLI runs as, plus free space and free inodes for a second copy of every sub-size while the run is in flight. - A current backup of
wp-content/uploads/and of thepostmetatable. Regeneration is destructive by default, and there is no undo.
How it works
WordPress keeps three separate things, and it pays to be precise about which one each step touches.
The registered sub-size list is code, not data. It comes from Settings > Media plus every add_image_size() call in your theme and plugins, and wp_get_registered_image_subsizes() returns the merged result. Nothing writes to it at runtime — adding a size only changes what future operations produce.
The files on disk are the original upload, an optional -scaled copy, and one file per registered size. An upload wider or taller than big_image_size_threshold (2560 px by default) gets a downscaled photo-scaled.jpg that becomes the full size, while the untouched upload stays as photo.jpg under the original_image key. wp_get_original_image_path() returns that real original, and it is what regeneration re-reads.
The _wp_attachment_metadata postmeta row is the index: a sizes array with one entry per variant, plus width, height and original_image. A theme builds srcset from this row, so a size whose file exists but is absent from the row is invisible to the front end, and vice versa.
Two consequences. Regeneration always works from the original, so sub-sizes never accumulate compression loss across repeated runs — unless an optimization plugin overwrote the original in place, in which case every future sub-size inherits that compression permanently. And it is CPU-bound in PHP with no queue and no concurrency: one process working through a list, which is why the batching below matters.
Step-by-step
-
Read the actual synopsis before choosing flags. Per the WP-CLI command reference, the command is
wp media regenerate [<attachment-id>...] [--image_size=<image_size>] [--skip-delete] [--only-missing] [--delete-unknown] [--yes]. There is no--dry-run, no--posts_per_pageand nowp media listsubcommand — write-ups mentioning them describe something that does not exist.--skip-deletedefaults to false, so a plain run deletes the old thumbnails.--only-missingsets--skip-deletefor you, and decides “missing” by checking both the metadata entry and the file on disk. -
Inventory the registered sizes — this is your multiplier. Every registered size is one more file per attachment, forever.
wp media image-sizeYou get a table of
name,width,height,cropandratio. A theme registering twelve sizes means twelve files per image before you optimise anything. Delete theadd_image_size()calls you do not use before regenerating, not after. -
Count the job, then do the disk and inode math.
wp post listaccepts anyWP_Queryargument, which is how you scope by MIME type.wp post list --post_type=attachment --post_status=any \ --post_mime_type=image --format=count du -sh wp-content/uploads/ ; df -h wp-content/uploads/ ; df -i wp-content/uploads/The count is your exact job size; under a few thousand, most of the batching below is unnecessary. Attachments times registered sizes is roughly the file count you end up with — a 100k-image library with eight sizes is around 900,000 files in
uploads/once you count originals and-scaledcopies.df -iis the check people skip: a filesystem can exhaust inodes with gigabytes of space still free, and the fix then is fewer registered sizes, not a bigger volume. -
Calibrate bytes on a sample instead of guessing. A sub-size costs whatever your JPEG quality and your photos’ compressibility make it cost, so measure fifty random attachments and extrapolate.
wp post list --post_type=attachment --post_status=any --post_mime_type=image \ --posts_per_page=50 --orderby=rand --format=ids | tr ' ' '\n' > /tmp/sample-ids.txt du -sb wp-content/uploads/ ; find wp-content/uploads/ -type f | wc -l time xargs wp media regenerate --yes < /tmp/sample-ids.txt du -sb wp-content/uploads/ ; find wp-content/uploads/ -type f | wc -lSuccess looks like
Success: Regenerated 50 of 50 images.plus two byte counts and two file counts you can subtract. Multiply the per-image seconds and bytes by your total from step 3. That estimate beats any published rule of thumb: it reflects your sizes, your source images and your hardware. -
Choose the narrowest run that fixes the problem. A full regeneration is rarely the right answer.
Targeting IDs directly is cheapest and combines with any of the flags:
wp media regenerate 123 124 125Found 3 images to regenerate. 1/3 Regenerated thumbnails for "Vertical Image" (ID 123). 2/3 Regenerated thumbnails for "Horizontal Image" (ID 124). 3/3 Regenerated thumbnails for "Beautiful Picture" (ID 125). Success: Regenerated 3 of 3 images.If exactly one registered size changed dimensions, rebuild only that variant instead of all of them:
wp media regenerate --image_size=large --yesThe progress output is the same, but each attachment does one encode instead of eight — on a large library, the difference between an afternoon and a weekend.
-
Build the ID list, then slice it into ranges. Feeding one enormous argument list to a single process gives you no checkpoint and no way to stop cleanly.
wp post list --post_type=attachment --post_status=any --post_mime_type=image \ --format=ids | tr ' ' '\n' > /tmp/attachment-ids.txt wc -l /tmp/attachment-ids.txt sed -n '1,20000p' /tmp/attachment-ids.txt > /tmp/regen-part-01.txt sed -n '20001,40000p' /tmp/attachment-ids.txt > /tmp/regen-part-02.txtwc -lshould print your count from step 3. Slicing the file beats re-querying, because the ID list is frozen at one point in time — uploads arriving during the run will not shift your ranges under you. To page at query time instead,wp post listalso accepts--offsetalongside--posts_per_page. -
Run a range under tmux, throttled. Each part is a night’s work you can start, watch, and stop.
tmux new -s regen nice -n 19 ionice -c3 xargs -n 200 wp media regenerate --only-missing --yes \ < /tmp/regen-part-01.txt 2>&1 | tee -a /tmp/regen-01.logEach batch of 200 is a separate WP-CLI process, so a fatal error costs one batch rather than the whole run, and PHP’s memory footprint resets between batches.
nice -n 19andionice -c3keep the job from starving PHP-FPM — regeneration is CPU-bound in the resizer and I/O-bound in the writes, and without them a full run makes the front end feel like it is down. Iftmuxis not installed,nohupis the equivalent:nohup nice -n 19 ionice -c3 xargs -n 200 wp media regenerate --only-missing --yes \ < /tmp/regen-part-01.txt > /tmp/regen-01.log 2>&1 &The shell prints a job number and PID, such as
[1] 21874. Note what--only-missingcosts you: because it implies--skip-delete, a size whose dimensions changed keeps its old file alongside the new one. When that is the point of the run, drop--only-missing, accept the deletion, and give up the cheap resume. -
Monitor from a second shell. Detach from tmux with
Ctrl-b dand watch without touching the job.grep -c 'Regenerated' /tmp/regen-01.log df -h wp-content/uploads/ ; df -i wp-content/uploads/ uptimeThat count against your range size is your progress bar. Watch both
dfoutputs — if either free figure trends toward zero, stop now rather than after the filesystem is full. To resume after any interruption, re-run the same command:--only-missingskips what is done, which makes the batch loop idempotent. There is no separate resume mode and none is needed. -
Flush caches and purge the CDN when the run finishes. New metadata does not reach visitors on its own.
wp cache type wp cache flushwp cache typeprints the backend in use —Redis,MemcachedorDefault— andwp cache flushanswersSuccess: The cache was flushed.On a shared Redis instance that flush hits every site on the database, so check the type first. Then purge the page cache through your caching plugin’s own command, and purge the CDN. The CDN step is the one people forget: if a size kept its dimensions the filename is unchanged, so edge nodes and browsers keep serving the old bytes at the same URL and the whole run looks like it did nothing.
Validate it works
Confirm one attachment end to end, then confirm the library.
wp eval 'print_r( wp_get_attachment_metadata( 123 ) );'
wp eval 'echo wp_get_attachment_image( 123, "large" ), PHP_EOL;'
The first prints the sizes array — every registered size should appear with a file, width, height and mime-type. The second prints the real <img> tag with the srcset your theme emits; a size present in the metadata but missing from srcset points at the theme, not regeneration.
Then prove there is nothing left to do:
xargs -n 200 wp media regenerate --only-missing --yes \
< /tmp/attachment-ids.txt 2>&1 | grep -c 'regeneration needed'
WP-CLI prints No thumbnail regeneration needed for ... for every attachment it skips, so a count equal to your attachment total means the library is complete. Any shortfall is the set that still fails, and the surrounding log lines name them.
Troubleshooting
-
Fatal error: Allowed memory size ... exhausted. One large source image can exceed PHP’s CLImemory_limitwhile decoding. Check which editor you actually get withwp eval 'echo get_class( wp_get_image_editor( wp_get_original_image_path( 123 ) ) ), PHP_EOL;'— Imagick is generally more memory-hungry per image than GD but handles more formats. Raise the ceiling for this run only, without touching site-wide config:php -d memory_limit=1024M "$(command -v wp)" media regenerate --only-missing --yes 123 124. -
No space left on devicepartway through. A default run deletes each attachment’s old sub-sizes before writing new ones, so peak usage is lower than a naive estimate — but adding sizes still grows the tree. Free space, then re-run with--only-missingto fill the gap. Ifdf -hshows free space and writes still fail, checkdf -i: you have exhausted inodes, and the fix is fewer registered sizes, not a bigger disk. -
A killed run left attachments with no thumbnails. Without
--only-missing, the process deletes an attachment’s sub-sizes and then writes them, so a kill in between leaves an original, a metadata row that still lists sizes, and no files. The front end falls back to the full-size image — slow, not broken. Re-run the same range with--only-missing: the gaps fill and the metadata row is rewritten on the way through, so the stalesizesentries correct themselves. This is why step 7 usestmuxornohup; WP-CLI has no daemon, and closing the terminal kills the process mid-batch. -
WP-CLI reports it cannot find the original file. Two causes. Either the file is not local — an offload plugin pointing the library at S3, R2 or B2, or a migration that moved the database and not
wp-content/uploads/, for which offloading WordPress media to S3, R2 or B2 covers how those plugins expect the tree to be arranged. Or an image-optimization plugin was set to remove originals after resizing and the pixels are gone. The second case has no recovery except restoringuploads/from backup; regeneration cannot invent detail that was deleted. Tell them apart withwp eval 'var_dump( file_exists( wp_get_original_image_path( 123 ) ) );'before planning anything. -
Images embedded in posts 404 after a size changed. WordPress writes a concrete filename into the post’s
<img src>at insert time. Regenerating with unchanged dimensions produces the same filename and nothing breaks — but movelargefrom 1024 to 1200 px and the new file isphoto-1200x800.jpgwhile the default run deletesphoto-1024x683.jpg, taking every hardcoded reference with it. Use--skip-deletewhen you cannot control who references those files, and fix existing content with a checked search-replace:wp search-replace 'photo-1024x683.jpg' 'photo-1200x800.jpg' --dry-runfirst, then again without--dry-run.
When this is the wrong approach
If a CDN or image service resizes on the fly — Cloudflare Images, a Bunny optimiser, imgix — generating dozens of static variants produces files nobody requests while still costing disk and inodes. Point the front end at the transform URL and shrink the registered size list instead.
If what you want is WebP or AVIF, regeneration alone will not produce it. Core supports both formats but does not convert JPEG or PNG uploads by default — that needs the Modern Image Formats plugin or an image_editor_output_format filter, after which regeneration is the step that applies the new format to existing attachments.
Past a certain size, a single WP-CLI loop is the wrong shape regardless of flags: the run wants to be a queued, restartable job with its own monitoring, not a terminal you have to keep alive. Operating a WordPress media library past 100k items covers that.
Running WordPress that earns real money deserves an operator — Stack Harbor runs that stack under Enterprise WordPress; book an infrastructure consult.