Skip to content

fix(sync): auto-regenerate thumbnail sizes left stale after an image edit - #1314

Open
gabrielcld2 wants to merge 3 commits into
developfrom
fix/regenerate-outdated-thumbnail-sizes
Open

gabrielcld2 wants to merge 3 commits into
developfrom
fix/regenerate-outdated-thumbnail-sizes

Conversation

@gabrielcld2

@gabrielcld2 gabrielcld2 commented Oct 12, 2026 •

Copy link
Copy Markdown
Collaborator

The issue

Editing an image via the WordPress image editor (crop/scale) can rename the main attached file (adding an -e{timestamp} suffix) without regenerating its registered thumbnail sizes.

The sizes metadata is left pointing at the pre-edit filenames, which no longer exist on disk and have no matching entry in wp_cloudinary_relationships.

Every render of that attachment then falls through to Delivery::find_attachment_size_urls(), which runs an uncached wp_postmeta query trying (and failing) to resolve the stale URL.

On high-traffic pages (e.g. a site icon used on every page) this becomes a query on every single request.

The fix

This adds a new sizes sync type, modeled directly on the existing edit sync type:

  • Media::has_outdated_sizes() (php/class-media.php) detects when the sizes metadata's filenames no longer match the current attached file's basename.
  • Upload_Sync::regenerate_sizes() (php/sync/class-upload-sync.php) calls wp_generate_attachment_metadata() to rebuild the sizes, then persists the new signature via set_signature_item() so it doesn't re-run on every subsequent render.

Because this rides the existing realtime sync pipeline, it self-heals both future edits and attachments that are already drifted today.

i.e. no new cron job, scheduled scan, or admin action required. No code changes needed outside these three files.

Limitations

  • already-drifted attachments that are never rendered anywhere won't be caught by this (nothing triggers the per-render check for them)
  • the image will appear fixed only from the second run. Given the current state this is a much better improvement that doesn't require us to maintain a complicated cron mechanism, so that seems an acceptable compromise.

QA notes

Prerequisites:

  • Cloudinary plugin installed and configured
  • One image uploaded to the Media Library and synced in Cloudinary
  • A block-based theme (e.g. Twenty Twenty-Five)
  • This repo should first be on the develop branch to reproduce the issue
  • The test script qa-check-sizes.php below added at the root of the repo:
<?php
function qa_has_outdated_sizes( $attachment_id ) {
	$metadata = wp_get_attachment_metadata( $attachment_id );
	if ( empty( $metadata['file'] ) || empty( $metadata['sizes'] ) ) {
		return false;
	}

	$base = wp_basename( $metadata['file'] );
	$ext  = pathinfo( $base, PATHINFO_EXTENSION );
	$base = ! empty( $ext ) ? substr( $base, 0, - ( strlen( $ext ) + 1 ) ) : $base;

	foreach ( $metadata['sizes'] as $size ) {
		if ( empty( $size['file'] ) || 0 !== strpos( $size['file'], $base . '-' ) ) {
			return true;
		}
	}

	return false;
}

$attachments = get_posts(
	array(
		'post_type'      => 'attachment',
		'posts_per_page' => 1,
		'orderby'        => 'modified',
		'order'          => 'DESC',
		'meta_key'       => '_wp_attachment_backup_sizes',
	)
);

if ( empty( $attachments ) ) {
	WP_CLI::error( 'No edited image attachment found. Crop or rotate an image (e.g. the Site Icon) first.' );
}

$attachment_id = $attachments[0]->ID;
$metadata      = wp_get_attachment_metadata( $attachment_id );

WP_CLI::log( "Attachment: #$attachment_id (" . get_the_title( $attachment_id ) . ')' );
WP_CLI::log( 'Current attached file: ' . get_post_meta( $attachment_id, '_wp_attached_file', true ) );
WP_CLI::log( '' );
WP_CLI::log( 'Registered sizes:' );
foreach ( $metadata['sizes'] as $size => $data ) {
	WP_CLI::log( "  $size => {$data['file']}" );
}
WP_CLI::log( '' );
WP_CLI::log( 'Outdated sizes (stale filenames from before the edit): ' . ( qa_has_outdated_sizes( $attachment_id ) ? 'YES - bug present' : 'no - in sync' ) );

Manual steps:

  1. Go to Settings → General and set the Site Icon to the previously uploaded and synced image
  2. Go to the Media Library, edit the image, crop and update it
  3. Run the check script below (npx wp-env run cli -- wp eval-file /var/www/html/wp-content/plugins/cloudinary_wordpress/qa-check-sizes.php) → should print Outdated sizes: YES - bug present.
  4. Visit any front-end page (the site icon renders in <head> on every page) to trigger a render.
  5. Run the check script again:
    • On develop: still YES - bug present — never fixes itself.
    • On this branch: now no - in sync, and the sizes list shows the new, edited filenames.

…edit

Editing an image via the WP image editor can rename the main file without
regenerating its registered thumbnail sizes, leaving `sizes` metadata
pointing at filenames that no longer exist. This causes
Delivery::find_attachment_size_urls() to run an uncached wp_postmeta
lookup on every render of that attachment, since nothing resolves the
stale URLs.

Adds a `sizes` sync type (mirroring the existing `edit` type) that
detects this drift on render via the existing realtime sync pipeline and
regenerates the attachment metadata, self-healing both new edits and
already-drifted attachments without any new cron job or bulk scan.
wp_get_attachment_metadata()'s PHPDoc already types 'sizes' as array,
making the is_array() check dead code; empty() already covers the
missing-key and empty-array cases.
@gabrielcld2
gabrielcld2 marked this pull request as ready for review October 12, 2026 12:38

@utkarshcloudinary utkarshcloudinary left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left 2 comments.

Comment thread php/class-media.php Outdated
$base = ! empty( $ext ) ? substr( $base, 0, - ( strlen( $ext ) + 1 ) ) : $base;

foreach ( $metadata['sizes'] as $size ) {
if ( empty( $size['file'] ) || 0 !== strpos( $size['file'], $base . '-' ) ) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

blocker: The prefix check marks a valid WP state as stale. When image_edit_thumbnails_separately is on and the user edits with target "All sizes except thumbnail" (nothumb), core keeps the old thumbnail on purpose. The main file and other sizes get the -e{timestamp} base.

I checked this locally (wp-env, WP 7.1):

file: 2026/10/pr1314-nothumb-2-e1791880319565.jpg
  medium       => pr1314-nothumb-2-e1791880319565-225x300.jpg
  thumbnail    => pr1314-nothumb-2-150x150.jpg
  medium_large => pr1314-nothumb-2-768x576.jpg
has_outdated_sizes: true
thumbnail after regenerate: pr1314-nothumb-2-e1791880319565-150x150.jpg

On the next render, regenerate_sizes() overwrites the user's unedited thumbnail with a crop of the edited image. The medium_large entry also keeps the old name in this output. The rotated 600px-wide image is too small for that size, so core does not regenerate it, and the old file stays on disk. A name-only check flags this case too.

Instead, check that each size file exists on disk (path_join( dirname( get_attached_file( $id ) ), $size['file'] )). This targets the real bug (no local file and no relationship row) and does not touch valid partial edits.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@utkarshcloudinary 👍 Good point. Implemented in 41a3742

Comment thread php/sync/class-upload-sync.php
- Media::has_outdated_sizes() now checks that each registered size's
  file actually exists on disk, instead of comparing filename
  prefixes. A prefix check misflags valid WordPress states as broken
  -- e.g. editing with "all sizes except thumbnail" deliberately
  keeps the old thumbnail, and a size too small to regenerate from
  the edited image is legitimately left as-is. Both would have been
  wrongly overwritten.

- Upload_Sync::regenerate_sizes() now preserves the rest of the
  attachment's metadata record instead of replacing it wholesale.
  wp_generate_attachment_metadata() writes its own metadata to the
  database as a side effect partway through execution, so "current"
  metadata must be captured before calling it, not after, or the
  capture already sees the clobbered record. Without this, keys like
  original_image (breaks wp_get_original_image_path()) and
  third-party plugin data were silently dropped.

Reported in PR review (#1314).

@utkarshcloudinary utkarshcloudinary left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left some feedback.

Comment thread php/class-media.php
Comment on lines +1718 to +1722
$dir = dirname( get_attached_file( $attachment_id ) );

foreach ( $metadata['sizes'] as $size ) {
if ( empty( $size['file'] ) || ! file_exists( path_join( $dir, $size['file'] ) ) ) {
return true;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

blocker: This flags every attachment offloaded with storage cld as outdated.

Sync\Storage::remove_local_assets() deletes the original and all size files through wp_delete_attachment_files(), but it never updates the stored metadata. The sizes array is still there, and the files are gone, so this check returns true.

What happens after the upgrade:

  • No attachment has a sizes signature yet (the default is the 5.25 priority float), so get_sync_type() reaches this validate during a normal render through maybe_prepare_sync().
  • regenerate_sizes() runs with a source file that does not exist. wp_generate_attachment_metadata() returns no sizes, so it returns a WP_Error.
  • log_sync_result() sets _cld_error. That blocks all later sync types for the attachment, and the error comes back after each clean up. The signature is never saved, so is_synced() stays false.

New uploads in cld mode are not affected, because sizes (5.25) runs before storage (15) while the files are still on disk. Existing offloaded libraries are affected.

Suggestion: return false when there is no source file. This is the same as Storage::validate(), and it also saves the signature:

$file = get_attached_file( $attachment_id );
if ( empty( $metadata['file'] ) || empty( $metadata['sizes'] ) || ! $file || ! file_exists( $file ) ) {
	return false;
}

$dir = dirname( $file );

Comment on lines +297 to +300
$file = get_attached_file( $attachment_id );
$regenerated = wp_generate_attachment_metadata( $attachment_id, $file );
if ( empty( $regenerated['sizes'] ) ) {
return new \WP_Error( 'cloudinary_regenerate_sizes_failed', __( 'Could not regenerate attachment sizes.', 'cloudinary' ) );

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

warning: The comment above says that wp_generate_attachment_metadata() writes metadata as a side effect, but this early return does not undo that write.

wp_create_image_subsizes() saves a new record with 'sizes' => array() ("Initial save of the new metadata") before it makes any subsize. If no sizes are made, for example because the edited image is smaller than all registered sizes or wp_get_image_editor() fails, the stored metadata is now that new record. original_image, the old sizes and data from other plugins are lost, and we return here before the merge.

Suggestion: restore $metadata before the error is returned:

if ( empty( $regenerated['sizes'] ) ) {
	wp_update_attachment_metadata( $attachment_id, $metadata );
	return new \WP_Error( ... );
}

Also, an image that is too small for every registered size is not an error. If we treat it as an error, the attachment gets _cld_error. It is better to save the signature in that case.

// wp_generate_attachment_metadata() builds a fresh metadata array, so only merge in the
// regenerated sizes rather than overwriting the whole record -- other keys (e.g. original_image,
// third-party plugin data) must be preserved.
$metadata['sizes'] = $regenerated['sizes'];

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

warning: This replaces the full sizes map, but has_outdated_sizes() is true when only one size file is missing.

Example: an image is edited with "All images except thumbnail". Core keeps the unedited thumbnail on purpose. If one more size is then missing, the code here makes all sizes again from the edited full image. The thumbnail that was kept on purpose is replaced by a cropped version. Sizes that are no longer registered, but still have files on disk, are also removed from the metadata.

Suggestion: unset only the entries whose files are missing, then make only those sizes again with _wp_make_subsizes( $missing, get_attached_file( $attachment_id ), $metadata, $attachment_id ). That function skips sizes that already exist and keeps the other keys, so you do not need the full regenerate and merge.

Do not use wp_update_image_subsizes() here. It uses wp_get_original_image_path(), which can return the pre-edit file when original_image is set.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants