WordPress same-name upload overwrites media? Disk-only dedup
Β· 11 min read
On a production site whose media library is offloaded to object storage in cloud-only mode (local copies deleted), an editor re-uploaded a cover image under a name that already existed months ago. The upload succeeded with no warning. That afternoon the site's theme vendor reported that a batch of older posts was showing the new image. The media library listed two separate attachments with different IDs; only readers noticed the pictures had changed.
TL;DRβ
- WordPress core's same-name dedup,
wp_unique_filename(), only scans the local upload directory. It never queries the database β the function body contains zero$wpdbcalls β and it knows nothing about your bucket. With local files deleted, the disk is always empty, so dedup always approves the name, the upload reuses the same object key, andputObjectoverwrites the old object. - The fix: hook
wp_unique_filename(priority 999) and add three checks β a disk directory family-name scan, a_wp_attached_filefamily-prefix query, and per-key HEAD requests against the bucket (base /-scaled/-rotatedΓ extension set). If any face is occupied, increment WordPress-native-Nnames up to 20 rounds; if a dedup source errors out, fall back to a random suffix and upload unblocked. - A pitfall worth copying: the object key equals the uploads-relative path, so the check set must carry the directory prefix. Our first version built keys from the bare basename, and a test fixture with a subdirectory immediately caught "bucket-face dedup misses every subdirectory upload" β
2026/11/hero.jpgandhero.jpgare unrelated strings to object storage.