Skip to content

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

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

gabrielcld2 wants to merge 2 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
$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.

return new \WP_Error( 'cloudinary_regenerate_sizes_failed', __( 'Could not regenerate attachment sizes.', 'cloudinary' ) );
}

wp_update_attachment_metadata( $attachment_id, $metadata );

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: wp_generate_attachment_metadata() builds a fresh array, so this call replaces the full metadata record. Keys that are not regenerated are lost.

I checked this locally with a 3000x2000 upload (big-image -scaled path) and a third-party key:

before keys: width,height,file,filesize,sizes,image_meta,original_image,third_party_key
after keys:  width,height,file,filesize,sizes,image_meta

If original_image is lost, wp_get_original_image_path() stops working. This plugin uses that path for uploads (filter_backup_original, get_original_image). Other plugins' metadata (for example WPML, or custom keys) is also lost.

Suggest: keep the current metadata and replace only sizes (and maybe width/height/filesize):

$current          = wp_get_attachment_metadata( $attachment_id );
$current['sizes'] = $metadata['sizes'];
wp_update_attachment_metadata( $attachment_id, $current );

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