Created
July 17, 2024 10:44
-
-
Save Niq1982/7da6df4325287597fc72958b16ab0c6b to your computer and use it in GitHub Desktop.
Replace original images with scaled version if WordPress has deleted the originals
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* This script will copy the scaled images to the original image path in case the original | |
* image is missing. It will also regenerate the thumbnails for the original image. | |
*/ | |
$ids = get_posts([ | |
'post_type' => 'attachment', | |
'post_status' => 'any', | |
'posts_per_page' => -1, | |
'fields' => 'ids', | |
'post_mime_type' => [ | |
'image/jpeg', | |
'image/png', | |
], | |
]); | |
foreach ($ids as $id) { | |
$file_path = wp_get_original_image_path($id); | |
if (file_exists($file_path)) { | |
// Original file exists so skip | |
continue; | |
} | |
echo "The original file {$file_path} for attachment {$id} does not exist, trying to replace with -scaled version"; | |
$mimetype = get_post_mime_type($id); | |
$file_type = str_replace('image/', '.', $mimetype); | |
$scaled_file_path = str_replace($file_type, "-scaled{$file_type}", $file_path); | |
if (!file_exists($scaled_file_path)) { | |
echo "Scaled file not found: {$scaled_file_path}, skipping\n"; | |
continue; | |
} | |
echo "Copying {$scaled_file_path} to {$file_path}\n"; | |
$copied = copy($scaled_file_path, $file_path); | |
if (!$copied) { | |
echo "Copying failed: {$scaled_file_path} to {$file_path}\n"; | |
continue; | |
} | |
if (!file_exists($file_path)) { | |
echo "Copying failed, file not found: {$file_path}\n"; | |
continue; | |
} | |
// Regenerate the thumbnails (optional, in case the thumbs are missing, just add continue; before this if you dont need replacing) | |
echo "Regenerating thumbnails for {$id}\n"; | |
$success = wp_create_image_subsizes($file_path, $id); | |
if (is_array($success) && !empty($success['sizes'])) { | |
echo count($success['sizes']) . " thumbnails regenerated for {$id}\n"; | |
} else { | |
echo "Failed to regenerate thumbnails for {$id}\n"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment