
A site that has published for eight years usually carries three or four thousand files it will never show again. Logos from a 2019 theme, product shots from a discontinued line, screenshots from a tutorial that was rewritten twice. None of them appear on a page, and every one of them is still in the backup.
The obvious move is to open the Media Library, filter by Unattached, and delete. That filter is the most misread screen in WordPress.
It does not mean “unused”. It means “no parent post was recorded at upload time”, which is a different and much narrower fact.
A WordPress media library cleanup that is safe enough to run on a live site takes an afternoon, not a bulk-select. This is the audit behind it.
What “Unattached” actually filters
Every attachment is a row in wp_posts with post_type = 'attachment'. That row has a post_parent column, and the Unattached view asks for rows where post_parent = 0.
Three things follow.
Parent is set by context, not by use. Upload an image from inside a post and WordPress can record that post as the parent. Upload it from the Media Library screen, or through a page builder that posts to its own upload endpoint, and the parent stays 0 even if the image ends up on twenty pages.
An attached image can still be unused. Upload a photo to a post, insert it, then delete the image block. The attachment keeps its parent and disappears from the Unattached view. It is now invisible to the filter that was supposed to find it.
An unattached image can be load-bearing. The site icon, the custom logo, a footer background in the Customizer, and most Elementor or Divi image widgets store an attachment ID in an option or in serialized meta. None of them set post_parent.
So the filter is a starting point, not a verdict. Treat every row it shows as a question: where is this file referenced?
What WordPress stores for one image
Before querying anything, know the four pieces of data involved.
| Where | Key | What it holds |
|---|---|---|
wp_posts | ID, post_title, post_mime_type, post_parent | The attachment record |
wp_postmeta | _wp_attached_file | Path relative to wp-content/uploads, such as 2026/12/photo.jpg |
wp_postmeta | _wp_attachment_metadata | Width, height, and the sizes array of generated files |
wp_posts | guid | The URL at upload time, unreliable after a domain move |
The two helper functions are the stable interface:
$id = 123;
$file = get_attached_file( $id ); // Absolute path, or false.
$meta = wp_get_attachment_metadata( $id ); // width, height, sizes, image_meta.
get_attached_file() resolves _wp_attached_file against the upload directory. It can return a path that no longer exists, which is exactly the kind of row a cleanup should catch. The function reference documents the filter that runs on the result, and the metadata reference explains the sizes array.
That array is why a file count never matches an attachment count. One JPEG can produce a dozen files on disk: the original, a -scaled copy for large uploads, -1024x768 and smaller thumbnails, a -rotated version after an edit, and timestamp-suffixed copies from the image editor. Deleting the row removes all of them through wp_delete_attachment_files(), which is convenient and also unforgiving.
Start with the database, not the file system
The first pass is a SQL query that returns attachments whose ID appears nowhere in post content. Run it on a staging copy, and change the table prefix if yours is not wp_.
SELECT a.ID,
a.post_title,
f.meta_value AS file
FROM wp_posts AS a
LEFT JOIN wp_postmeta AS f
ON f.post_id = a.ID
AND f.meta_key = '_wp_attached_file'
WHERE a.post_type = 'attachment'
AND NOT EXISTS (
SELECT 1
FROM wp_posts AS c
WHERE c.post_status NOT IN ( 'trash', 'auto-draft' )
AND c.post_type <> 'attachment'
AND c.post_content LIKE CONCAT( '%', a.ID, '%' )
)
ORDER BY a.ID DESC;
This query is deliberately crude, and the crudeness runs in your favor. LIKE '%123%' also matches 1123, 1234, a price of 123, and the year 2023. Every false match keeps an image out of the candidate list, so the query under-reports rather than over-reports.
On a 4,000-image library it might return 900 rows. Most of those 900 will still be in use somewhere the query cannot see.
The second pass checks featured images, because _thumbnail_id lives in post meta rather than content:
SELECT post_id
FROM wp_postmeta
WHERE meta_key = '_thumbnail_id'
AND meta_value = 123;
Swap 123 for the candidate ID. A non-empty result means the image is the featured image of at least one post.
Deleting it does not just remove the file: wp_delete_attachment() runs delete_metadata( 'post', 0, '_thumbnail_id', $post_id, true ), which clears that meta value across every post on the site. The featured image silently disappears from archives and social cards.
The reference surfaces a content search cannot see
Post content is the easiest place for an image to hide, and the least complete. These are the other places a valid reference can live.
| Surface | How the image is stored | How to check |
|---|---|---|
| Post content | <img> URL, wp-image-123 class, gallery shortcode, block JSON | Search post_content for ID and filename |
| Featured image | _thumbnail_id post meta | SQL on wp_postmeta |
| Site icon | site_icon option, plain attachment ID | get_option( 'site_icon' ) |
| Theme logo and header | theme_mods_<theme>, serialized | get_theme_mod( 'custom_logo' ) |
| Page builder layouts | _elementor_data, _et_pb_*, similar meta | Search wp_postmeta.meta_value for the ID or filename |
| Widgets and menus | widget_* options, nav_menu_item meta | Search wp_options and menu meta |
| Term and user meta | Custom fields on categories or profiles | Search wp_termmeta and wp_usermeta |
| Customizer CSS | custom_css post type, background-image: url(...) | Search the post content of custom_css |
| Theme and plugin files | Hardcoded get_template_directory_uri() paths | Search the codebase, not the database |
| External sites | Hotlinked URL | Access logs are the only evidence |
The option check is short enough to run by hand:
$id = 123;
if ( (int) get_option( 'site_icon' ) === $id ) {
// Used as the favicon and app icon.
}
if ( (int) get_theme_mod( 'custom_logo' ) === $id ) {
// Used as the theme logo.
}
For everything else, a serialized search is noisy but safe:
SELECT option_name
FROM wp_options
WHERE option_value LIKE '%123%';
That will match unrelated numbers. It will also catch the page builder that stored "id":123 inside a JSON blob, which is the point. Investigate each hit instead of trusting the count.
Search by filename, not only by ID
Page builders and hand-written HTML usually store the file URL, not the attachment ID. A content search for the ID misses them completely.
The reliable key is the filename stem. Take the path from _wp_attached_file, strip the extension and any derivative suffix, and search for the stem in post content and in meta values.
$file = get_attached_file( 123 );
$stem = pathinfo( $file, PATHINFO_FILENAME );
$stem = preg_replace( '/-(scaled|rotated|\d+x\d+|e\d+)$/', '', $stem );
A stem like product-shot-2024 is a strong signal. A stem like IMG_0001 is not: it will match an unrelated upload from the same camera. That failure mode keeps too much, which is the correct direction to fail.
Then run the search across both tables:
SELECT ID, post_title
FROM wp_posts
WHERE post_status NOT IN ( 'trash', 'auto-draft' )
AND post_type <> 'attachment'
AND post_content LIKE '%product-shot-2024%';
If that returns nothing, repeat against wp_postmeta.meta_value. Elementor keeps its layout as a JSON blob in _elementor_data, so a filename that never appears in post_content can still be the hero image of the homepage.
A runnable audit script
The manual queries get you a shortlist. This script turns the shortlist into a report you can read line by line. Save it as audit-media.php and run it with wp eval-file audit-media.php.
<?php
global $wpdb;
$ids = $wpdb->get_col(
"SELECT ID FROM {$wpdb->posts}
WHERE post_type = 'attachment'
ORDER BY ID DESC"
);
foreach ( $ids as $id ) {
$file = get_attached_file( $id );
if ( ! $file || ! file_exists( $file ) ) {
WP_CLI::line( "MISSING_FILE\t{$id}" );
continue;
}
$stem = pathinfo( $file, PATHINFO_FILENAME );
$stem = preg_replace( '/-(scaled|rotated|\d+x\d+|e\d+)$/', '', $stem );
$in_content = (int) $wpdb->get_var( $wpdb->prepare(
"SELECT COUNT(*) FROM {$wpdb->posts}
WHERE post_status NOT IN ( 'trash', 'auto-draft' )
AND post_type <> 'attachment'
AND post_content LIKE %s",
'%' . $wpdb->esc_like( $stem ) . '%'
) );
$featured = (int) $wpdb->get_var( $wpdb->prepare(
"SELECT COUNT(*) FROM {$wpdb->postmeta}
WHERE meta_key = '_thumbnail_id' AND meta_value = %d",
$id
) );
if ( 0 === $in_content && 0 === $featured ) {
WP_CLI::line( "CANDIDATE\t{$id}\t{$stem}" );
}
}
Two outputs matter. MISSING_FILE is an attachment row whose file is gone, usually after a manual migration or an aggressive server cleanup. CANDIDATE is a row with no content and no featured-image hit.
Neither is permission to delete; both are a reason to look.
Run the same script against a staging database, not production, and redirect the output to a file you can annotate.
Files on disk with no database row
The opposite problem is just as common. Failed uploads, FTP copies, and half-finished migrations leave files in wp-content/uploads that no attachment row points to. WordPress will never show them, back them up as media, or delete them.
List the difference between disk and database:
wp db query \
"SELECT meta_value FROM wp_postmeta WHERE meta_key = '_wp_attached_file'" \
--skip-column-names > known.txt
find wp-content/uploads -type f \
| sed 's#.*/wp-content/uploads/##' \
| sort > on-disk.txt
comm -23 on-disk.txt <(sort known.txt)
The result is not a clean orphan list. Every generated thumbnail shows up as a difference because only the original path is stored in _wp_attached_file.
Before deleting, discard any path whose filename matches a known original’s stem plus -WxH, -scaled, -rotated, or -e<timestamp>. What remains is the real candidate set.
Because these files have no attachment ID, nothing in WordPress can reference them except a hardcoded URL in a template or a stylesheet. Grep the theme for the filename before you move anything.
Regenerate before you delete
A surprising number of “unused” images are actually broken sizes. The theme changed its image dimensions, the old thumbnails no longer match, and the page falls back to the full-size file. Cleaning up the library is a good moment to repair that.
wp media regenerate --only-missing
--only-missing creates the sizes that are absent without touching files that already exist. After a theme switch, that is usually all you need. If the site has accumulated sizes from three retired themes, list what is registered, then remove the rest:
wp media image-size
wp media regenerate --delete-unknown
The regenerate command reference documents the flags, including --update-attachment-refs (added in WP-CLI 3.0.0), which rewrites references to regenerated thumbnails inside post content. That flag matters when the editor stored a URL to a specific size and regeneration produced a different filename. The image-size command lists the registered sizes and their crop settings, which is how you decide what should exist in the first place.
Regeneration also exposes missing originals. When the file is gone, the command reports the attachment and moves on; that output is a free list of rows to repair or remove.
Delete in a way you can undo
Deleting media in WordPress is permanent by default. The MEDIA_TRASH constant is false unless a site defines it otherwise, so the Media Library bulk action says “Delete permanently” and the Trash view does not appear. wp_delete_attachment() respects the same rule: without MEDIA_TRASH, the file and row are removed immediately.
That is a reason to work in this order.
- Back up the database and the uploads directory. A database export alone is not enough; the files are the part you are about to destroy. The backup plugin guide covers the options if the host does not provide snapshots.
- Export the candidate list with ID, filename, title, and upload date.
- Move candidates out of
uploadsinto a quarantine folder outside the web root, or delete them on staging only. - Watch the logs for a week. A 404 on a quarantined file is the signal that something still references it.
- Delete the row only after the file has survived the observation window.
For a single attachment, the WP-CLI command is:
wp post delete 123 --force
Attachments are routed to wp_delete_attachment() by wp_delete_post(), so the result is a permanent delete even without MEDIA_TRASH. In PHP, the explicit call is:
wp_delete_attachment( 123, true );
The function reference lists the hooks that fire, which is useful if a plugin stores its own copy of the file path. Any integration that caches attachment URLs needs to be cleared after the delete.
What cleanup does and does not fix
Removing unused images does not make a page faster. A file that is never requested has no effect on Largest Contentful Paint, Total Blocking Time, or any other field metric. If the goal is speed, the work is choosing the right formats and dimensions for the images that do load, which is the subject of the image optimization guide.
What cleanup does fix:
- Backup and migration size. Uploads usually outgrow the database, and every copy of the site carries the dead weight.
- Media library noise. Editors stop scrolling past a decade of retired logos to find this month’s photo.
- Attachment pages. If attachment pages are enabled, deleting an attachment removes a thin page that can surface in search. WordPress 6.4 added the
wp_attachment_pages_enabledoption; sites upgraded from earlier versions usually have it set to1, while newer installs ship with pages off and redirect the attachment URL to the file. - Image search exposure. A deleted image can drop out of Google Images. Check the Image tab in Search Console before removing a photo that might be earning traffic, and follow the image SEO guidance if a photo needs to stay discoverable.
What it does not fix is a bloated wp_posts table full of revisions, transients, and orphaned meta. That is a separate job, covered in the WordPress database cleanup guide. Running both is reasonable; confusing one for the other is not.
The decision table
| What the audit found | Action |
|---|---|
| Appears in post content, a block, or a gallery | Keep |
Set as _thumbnail_id on any post | Keep |
Stored in site_icon or custom_logo | Keep |
| Present only in page builder meta | Keep |
| No reference, uploaded in the last 30 days | Wait; the post may still be a draft |
| No reference, older, no log hits | Quarantine, then delete |
| Row exists, file missing | Restore from backup or delete the row |
| File on disk, no row, not a derivative | Quarantine, then delete |
| Hotlinked by another site | Keep, or warn the site owner first |
| Referenced only in a draft | Keep until the draft is published or discarded |
The 30-day rule is not superstition. Editors upload an image, get interrupted, and finish the post next week. A cleanup that runs on the first of the month will delete the image on the second.
Test the result on the front end
After deletion, the database will look clean and the site can still be broken. Walk the pages that used the most media: the homepage, the blog index, a long guide, a product page, and any page with a gallery.
Check for broken image icons, missing featured images in archive cards, and social previews that now point at nothing. The functionality and speed check lists the broader pass, including the redirects and 404s that a media cleanup can leave behind.
If the site has a staging environment, do the whole cleanup there first and click through it. A staging copy also lets you compare the uploads directory size before and after, which is the only honest measure of whether the work was worth doing.
Manage the library so the next cleanup is smaller
The audit is cheaper when the library has rules.
- Name files for what they show, not for the camera’s counter.
- Set a maximum upload dimension in the media settings so a 6,000-pixel phone photo does not become the source for every thumbnail.
- Remove an image from the Media Library when its post is permanently deleted, rather than leaving the attachment behind.
- Review the Unattached view once a quarter, with the reference checks above, instead of once a decade in a panic.
The media upload management guide covers the workflow side, including who is allowed to upload and how to keep contributor uploads from filling the library. The download guide is useful when the library needs to leave the site entirely, such as during a migration.
FAQ
Is it safe to delete unattached images in WordPress?
Not without checking. “Unattached” only means post_parent is 0, so the image can still be the site icon, the theme logo, a page builder background, or a file inserted by URL. Check content, meta, options, and logs before deleting.
How do I find unused images in the WordPress media library?
Start with a SQL query for attachments whose ID does not appear in post content, then remove the ones referenced by _thumbnail_id, options, and page builder meta. Search by filename stem as well as ID, because builders store URLs rather than IDs. No single query is complete.
Does deleting an image break a featured image?
Yes, if that image is set as _thumbnail_id. wp_delete_attachment() deletes every _thumbnail_id meta row that points at the attachment, across all posts. The post stays published with no featured image, and archive cards and social previews lose their image.
What happens to the actual files when I delete an attachment?
WordPress deletes the original, the -scaled copy, every registered thumbnail, rotated versions, and backup sizes. The removal happens through wp_delete_attachment_files(). If the files are served from a CDN, purge the CDN cache as well.
Why does the Media Library say “Delete permanently” instead of Trash?
Because MEDIA_TRASH is false by default. Media does not use the trash unless a site explicitly enables it. A delete from the Media Library or WP-CLI is immediate, so take a backup of the uploads directory first.
How do I clean up files that have no attachment record?
Compare the files in wp-content/uploads against the paths stored in _wp_attached_file, then discard generated thumbnails from the difference. Anything left is a true orphan. Move it to quarantine and watch the logs before deleting it.
Does media cleanup improve Core Web Vitals?
No, not directly. Unused files are never requested, so they do not affect loading metrics. The gains are smaller backups, faster migrations, a cleaner library, and fewer thin attachment pages; speed work belongs to the images that actually render.
Can I regenerate thumbnails before deleting anything?
Yes, and you should. wp media regenerate --only-missing creates sizes the current theme expects, and --delete-unknown removes files for sizes no longer registered. Regeneration also reports attachments whose original file is missing, which is a useful repair list.